import sys

with open('localSetup.js', 'r', encoding='utf-8') as f:
    js = f.read()

# 1. Modify fetchSubscriptionStatus
old_status = '''      if (expiry && expiry > now) {
        statusBadge.textContent = 'AKTIF PRO';
        statusBadge.className = 'sub-badge-active';
        expiryRow.style.display = 'flex';
        expiryDate.textContent = expiry.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
        if (noticeEl) noticeEl.style.display = 'none';
        updatePurchaseButton(true);
      } else if (expiry) {'''

new_status = '''      if (expiry && expiry > now) {
        if (data.isTrial) {
            statusBadge.textContent = 'AKTIF (TRIAL 1 HARI)';
            statusBadge.className = 'sub-badge-active';
            statusBadge.style.background = '#0984e3'; // Blue
            updatePurchaseButton(false); // Enable the button for trial users
        } else {
            statusBadge.textContent = 'AKTIF PRO';
            statusBadge.className = 'sub-badge-active';
            statusBadge.style.background = 'var(--green)';
            updatePurchaseButton(true);
        }
        expiryRow.style.display = 'flex';
        expiryDate.textContent = expiry.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
        if (noticeEl) noticeEl.style.display = 'none';
      } else if (expiry) {'''
js = js.replace(old_status, new_status)

# 2. Modify updatePurchaseButton
old_btn = '''function updatePurchaseButton(isPro) {
  const buyBtn = document.getElementById('buySubBtn');
  if (isPro) {
    buyBtn.disabled = true;
    buyBtn.innerHTML = '✅ Berlangganan';
    buyBtn.className = 'btn btn-outline';
  } else {
    buyBtn.disabled = false;
    buyBtn.innerHTML = '⚡ Sewa API Sekarang';
    buyBtn.className = 'btn btn-green';
  }
}'''

new_btn = '''function updatePurchaseButton(isPro) {
  const buyBtn = document.getElementById('buySubBtn');
  if (isPro) {
    buyBtn.disabled = true;
    buyBtn.innerHTML = '✅ Berlangganan';
    buyBtn.className = 'btn btn-outline';
  } else {
    buyBtn.disabled = false;
    buyBtn.innerHTML = '⚡ Sewa API Sekarang';
    buyBtn.className = 'btn btn-green';
  }
}'''
# Actually we don't need to modify updatePurchaseButton, it's fine. It's called with `updatePurchaseButton(false)` for trial users.

# 3. Add trial activation logic inside auth.onAuthStateChanged
old_auth = '''      if (subSnap.exists) {
        const subData = subSnap.data();
        const expiry = subData.subscriptionExpiry ? new Date(subData.subscriptionExpiry) : null;
        if (expiry && expiry > new Date()) {
          isPro = true;
        }
      }

      if (isPro) {'''

new_auth = '''      if (subSnap.exists) {
        const subData = subSnap.data();
        const expiry = subData.subscriptionExpiry ? new Date(subData.subscriptionExpiry) : null;
        if (expiry && expiry > new Date()) {
          isPro = true;
        }
      }

      // --- TRIAL ACTIVATION LOGIC ---
      if (!isPro) {
        try {
          const deviceId = await getOrCreateDeviceId();
          // Find proxy url to use for api
          const configSnap = await db.collection('proxyConfig').get();
          let proxyBaseUrl = '';
          configSnap.forEach(doc => {
            if (!proxyBaseUrl && doc.data().proxyUrl) {
               const url = new URL(doc.data().proxyUrl);
               proxyBaseUrl = url.origin;
            }
          });
          
          if (proxyBaseUrl) {
             const res = await fetch(proxyBaseUrl + '/api/start-trial', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email: user.email, deviceHash: deviceId })
             });
             const trialRes = await res.json();
             if (trialRes.ok) {
                 isPro = true;
                 fetchSubscriptionStatus(user.email);
                 showStatus('proxy-status', '✅ Free Trial 1 Hari Berhasil Diaktifkan!', 'success');
                 
                 const noticeEl = document.getElementById('subExpiredNotice');
                 if (noticeEl) {
                     noticeEl.style.display = 'block';
                     noticeEl.style.background = 'rgba(9, 132, 227, 0.1)';
                     noticeEl.style.borderColor = 'rgba(9, 132, 227, 0.3)';
                     noticeEl.style.color = '#74b9ff';
                     noticeEl.innerHTML = '✨ <b>Masa Percobaan (Trial 1 Hari) Aktif!</b><br>Nikmati fitur AI tanpa batas. Beli paket sekarang agar tidak terputus besok.';
                 }
             } else {
                 if (trialRes.code !== 'TRIAL_USED' && trialRes.code !== 'TRIAL_USED_USER') {
                     console.log("Trial claim failed:", trialRes.message);
                 }
             }
          }
        } catch(e) {
          console.error("Error claiming trial:", e);
        }
      }

      if (isPro) {'''
js = js.replace(old_auth, new_auth)

# 4. We should also enhance `getOrCreateDeviceId` to be more robust for fingerprinting
old_device_id = '''// Function to get or create a unique Device ID for this browser profile
async function getOrCreateDeviceId() {
  return new Promise((resolve) => {
    chrome.storage.local.get(['deviceId'], (res) => {
      if (res.deviceId) {
        resolve(res.deviceId);
      } else {
        const newId = 'dev_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now().toString(36);
        chrome.storage.local.set({ deviceId: newId }, () => resolve(newId));
      }
    });
  });
}'''

new_device_id = '''// Function to generate hardware fingerprint and get Device ID
async function getOrCreateDeviceId() {
  return new Promise(async (resolve) => {
    chrome.storage.local.get(['deviceId'], async (res) => {
      if (res.deviceId) {
         resolve(res.deviceId);
      } else {
         const components = [
           navigator.hardwareConcurrency || 'unknown',
           navigator.deviceMemory || 'unknown',
           screen.width,
           screen.height,
           screen.colorDepth,
           Intl.DateTimeFormat().resolvedOptions().timeZone
         ];
         try {
           const canvas = document.createElement('canvas');
           const gl = canvas.getContext('webgl');
           if (gl) {
             const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
             if (debugInfo) components.push(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL));
           }
         } catch(e) {}
         
         const rawString = components.join('|');
         const msgBuffer = new TextEncoder().encode(rawString);
         const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
         const hashArray = Array.from(new Uint8Array(hashBuffer));
         const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
         
         const newId = 'dev_' + hashHex.substring(0, 16);
         chrome.storage.local.set({ deviceId: newId }, () => resolve(newId));
      }
    });
  });
}'''
js = js.replace(old_device_id, new_device_id)

with open('localSetup.js', 'w', encoding='utf-8') as f:
    f.write(js)

print('Updated localSetup.js with Trial Logic')
