importScripts("protection/extension-fingerprint.js", "guard-core.js", "ai-router.js");

const PRODUCT_ID = "utxo-guard";
const PRODUCT_NOTICE = "UTXO Guard licensed technology by Vestige Index. Redistribution, rebranding or commercial resale requires a valid license.";
const DEFAULT_LICENSE_URL = "https://utxo-ai-brain.inf-vestigeindex.workers.dev/api/utxo-ai/license";

const DEFAULT_STATE = {
  deviceId: null,
  licenseKey: null,
  licenseTier: "free",
  licenseVerifiedAt: null,
  licenseWalletAddress: null,
  connectedWallet: null,
  licenseState: {
    valid: false,
    tier: "free",
    issuer: "Vestige Index",
    watermark: PRODUCT_NOTICE,
  },
  buildFingerprint: self.UTXO_EXTENSION_FINGERPRINT,
  integrityStatus: self.verifyUtxoExtensionIntegrity?.() || { valid: true },
  analysisHistory: [],
  settings: {
    theme: "auto",
    autoAnalyze: true,
    showPageBadge: true,
    preferredModel: "llama3.1",
    bridgeEnabled: true,
    bridgeUrl: "https://utxo-ai-brain.inf-vestigeindex.workers.dev/api/utxo-ai/explain",
  },
};

function createDeviceId() {
  const bytes = new Uint8Array(18);
  crypto.getRandomValues(bytes);
  return `utxo-device-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}

function getStorage(keys) {
  return new Promise((resolve) => chrome.storage.local.get(keys, resolve));
}

function setStorage(value) {
  return new Promise((resolve) => chrome.storage.local.set(value, resolve));
}

async function ensureDeviceId() {
  const data = await getStorage(["deviceId"]);
  if (data.deviceId) return data.deviceId;
  const deviceId = createDeviceId();
  await setStorage({ deviceId });
  return deviceId;
}

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.local.get(Object.keys(DEFAULT_STATE), (current) => {
    chrome.storage.local.set({
      ...DEFAULT_STATE,
      ...Object.fromEntries(Object.entries(current).filter(([, value]) => value !== undefined)),
      deviceId: current.deviceId || createDeviceId(),
      buildFingerprint: self.UTXO_EXTENSION_FINGERPRINT,
      integrityStatus: self.verifyUtxoExtensionIntegrity?.() || { valid: true },
      settings: { ...DEFAULT_STATE.settings, ...(current.settings || {}) },
    });
  });
});

function trimHistory(history, next) {
  return [...(history || []), next].slice(-50);
}

async function analyzeUrl(payload) {
  const input = {
    url: payload.url,
    chain: payload.chain,
    action: payload.action,
    token: payload.token,
    provider: payload.provider,
    pageText: String(payload.pageText || "").slice(0, 12000),
    secretPromptText: String(payload.secretPromptText || "").slice(0, 4000),
    uiSignals: payload.uiSignals || [],
    amountUSD: payload.amountUSD,
    slippageBps: payload.slippageBps,
  };
  const result = self.analyzeUTXOGuard(input);
  const state = await new Promise((resolve) => {
    chrome.storage.local.get(["settings", "licenseKey", "licenseState"], (data) =>
      resolve({
        settings: { ...DEFAULT_STATE.settings, ...(data.settings || {}) },
        licenseKey: data.licenseKey || "",
        licenseState: data.licenseState || DEFAULT_STATE.licenseState,
      }),
    );
  });
  const settings = state.settings;
  const ai = await self.explainWithUtxoAI(result, {
    model: payload.model || settings.preferredModel,
    language: payload.language,
    bridgeEnabled: settings.bridgeEnabled,
    bridgeUrl: settings.bridgeUrl,
    licenseKey: state.licenseKey,
    productId: PRODUCT_ID,
    origin: payload.url || "",
  });
  const enriched = {
    ...result,
    ai,
    productId: PRODUCT_ID,
    watermark: PRODUCT_NOTICE,
    license: state.licenseState,
    analyzedAt: Date.now(),
    url: payload.url,
  };

  chrome.storage.local.get(["analysisHistory"], (data) => {
    chrome.storage.local.set({
      lastAnalysis: enriched,
      analysisHistory: trimHistory(data.analysisHistory, {
        url: payload.url,
        risk: enriched.risk,
        riskPercent: enriched.riskPercent,
        score: enriched.score,
        decision: enriched.decision,
        scoringEngine: enriched.scoringEngine,
        aiMode: ai.mode,
        provider: ai.provider,
        timestamp: enriched.analyzedAt,
      }),
    });
  });

  return enriched;
}

async function validateLicenseKey(licenseKey, origin = "") {
  if (!licenseKey) {
    return DEFAULT_STATE.licenseState;
  }

  const deviceId = await ensureDeviceId();

  try {
    const response = await fetch(DEFAULT_LICENSE_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-UTXO-Client": "utxo-guard-extension",
      },
      body: JSON.stringify({
        licenseKey,
        productId: PRODUCT_ID,
        origin,
        deviceId,
        client: "extension",
      }),
    });
    if (!response.ok) throw new Error(`License check returned ${response.status}`);
    const data = await response.json();
    return data.license || DEFAULT_STATE.licenseState;
  } catch {
    return {
      ...DEFAULT_STATE.licenseState,
      message: "License backend unavailable. Free read-only mode remains active.",
    };
  }
}

function normalizeAddress(value) {
  return String(value || "").trim().toLowerCase();
}

async function connectWalletInTab(tabId) {
  if (!tabId) {
    throw new Error("Open a Web3 page with your wallet available, then try again.");
  }

  const [result] = await chrome.scripting.executeScript({
    target: { tabId },
    world: "MAIN",
    func: async () => {
      const provider = globalThis.ethereum;
      if (!provider?.request) {
        return { ok: false, error: "No injected wallet detected on this page." };
      }
      const accounts = await provider.request({ method: "eth_requestAccounts" });
      const chainIdHex = await provider.request({ method: "eth_chainId" }).catch(() => "");
      const address = Array.isArray(accounts) ? accounts[0] : "";
      return {
        ok: Boolean(address),
        address,
        chainId: chainIdHex ? Number.parseInt(String(chainIdHex), 16) : null,
      };
    },
  });

  const value = result?.result || {};
  if (!value.ok || !value.address) {
    throw new Error(value.error || "Wallet connection was not completed.");
  }
  return {
    address: value.address,
    chainId: value.chainId || null,
    connectedAt: Date.now(),
  };
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message?.type === "UTXO_ANALYZE_PAGE") {
    analyzeUrl({
      ...message,
      url: message.url || sender.tab?.url || "",
      language: message.language,
    })
      .then((result) => {
        if (sender.tab?.id) {
          try {
            chrome.tabs.sendMessage(sender.tab.id, { type: "UTXO_ANALYSIS_RESULT", result }, () => {
              // Protected browser pages may not have a content script. Consume lastError to avoid noisy MV3 runtime errors.
              void chrome.runtime.lastError;
            });
          } catch {
            // The content script may not be attached on protected browser pages.
          }
        }
        sendResponse({ ok: true, result });
      })
      .catch((error) => {
        sendResponse({ ok: false, error: error instanceof Error ? error.message : "Analysis failed" });
      });
    return true;
  }

  if (message?.type === "UTXO_GET_STATE") {
    ensureDeviceId().then(() => {
      chrome.storage.local.get(null, (data) =>
        sendResponse({
          ok: true,
          data: {
            ...data,
            buildFingerprint: data.buildFingerprint || self.UTXO_EXTENSION_FINGERPRINT,
            integrityStatus: data.integrityStatus || self.verifyUtxoExtensionIntegrity?.(),
          },
        }),
      );
    });
    return true;
  }

  if (message?.type === "UTXO_PAGE_WALLET_SESSION") {
    const session = message.session || {};
    if (session.address) {
      setStorage({
        connectedWallet: {
          address: session.address,
          chainId: session.chainId || null,
          connectedAt: session.lastConnectedAt || Date.now(),
          domain: sender.tab?.url || message.origin || "",
          source: "vestige-index-bridge",
        },
      }).then(() => sendResponse({ ok: true }));
      return true;
    }
    sendResponse({ ok: false });
    return true;
  }

  if (message?.type === "UTXO_CONNECT_WALLET") {
    connectWalletInTab(message.tabId || sender.tab?.id)
      .then((connectedWallet) =>
        setStorage({ connectedWallet }).then(() => sendResponse({ ok: true, connectedWallet })),
      )
      .catch((error) => sendResponse({ ok: false, error: error instanceof Error ? error.message : "Wallet connection failed" }));
    return true;
  }

  if (message?.type === "UTXO_SAVE_LICENSE") {
    const licenseKey = String(message.licenseKey || "").trim();
    Promise.all([
      validateLicenseKey(licenseKey, message.origin || sender.tab?.url || ""),
      getStorage(["licenseKey", "licenseState", "licenseVerifiedAt", "licenseWalletAddress", "connectedWallet"]),
    ])
      .then(([validatedLicense, current]) => {
        const walletAddress = normalizeAddress(message.walletAddress || current.connectedWallet?.address || "");
        const storedWalletAddress = normalizeAddress(current.licenseWalletAddress || current.licenseState?.wallet || "");
        if (storedWalletAddress && walletAddress && storedWalletAddress !== walletAddress) {
          return {
            licenseState: {
              ...current.licenseState,
              valid: false,
              linkedWalletMismatch: true,
              message: "License already linked to another wallet.",
            },
            licenseVerifiedAt: current.licenseVerifiedAt || null,
          };
        }
        const sameKey = current.licenseKey && current.licenseKey === licenseKey;
        const cachedValid = sameKey && current.licenseState?.valid && validatedLicense?.valid === false;
        const licenseState = cachedValid
          ? {
              ...current.licenseState,
              message: "Cached premium access is active on this device. The license backend will be checked again later.",
            }
          : validatedLicense;
        const licenseVerifiedAt = licenseState.valid ? Date.now() : null;
        return setStorage({
          licenseKey: licenseKey || null,
          licenseTier: licenseState.tier || "free",
          licenseWalletAddress: walletAddress || storedWalletAddress || null,
          licenseState: {
            ...licenseState,
            wallet: walletAddress || storedWalletAddress || licenseState.wallet || "",
          },
          licenseVerifiedAt: licenseVerifiedAt || current.licenseVerifiedAt || null,
        }).then(() => ({
          licenseState: {
            ...licenseState,
            wallet: walletAddress || storedWalletAddress || licenseState.wallet || "",
          },
          licenseVerifiedAt: licenseVerifiedAt || current.licenseVerifiedAt || null,
        }));
      })
      .then((licenseState) => {
        sendResponse({ ok: true, license: licenseState.licenseState, licenseVerifiedAt: licenseState.licenseVerifiedAt });
      })
      .catch((error) => sendResponse({ ok: false, error: error instanceof Error ? error.message : "License validation failed" }));
    return true;
  }

  if (message?.type === "UTXO_SAVE_SETTINGS") {
    chrome.storage.local.get(["settings"], (data) => {
      chrome.storage.local.set(
        {
          settings: {
            ...DEFAULT_STATE.settings,
            ...(data.settings || {}),
            ...(message.settings || {}),
          },
        },
        () => sendResponse({ ok: true }),
      );
    });
    return true;
  }

  if (message?.type === "UTXO_CHECK_AI") {
    chrome.storage.local.get(["settings"], (data) => {
      const settings = { ...DEFAULT_STATE.settings, ...(data.settings || {}) };
      self
        .explainWithUtxoAI(
          { score: 95, riskPercent: 5, risk: "low", decision: "allow", warnings: [], scoringEngine: "UTXO Score AI deterministic v1" },
          {
            prompt: "Reply with one short readiness sentence.",
            model: settings.preferredModel,
            bridgeEnabled: settings.bridgeEnabled,
            bridgeUrl: settings.bridgeUrl,
          },
        )
        .then((ai) => sendResponse({ ok: true, ai }))
        .catch((error) => sendResponse({ ok: false, error: String(error) }));
    });
    return true;
  }

  if (message?.type === "UTXO_GET_INSTALL_OPTIONS") {
    sendResponse({
      ok: true,
      options: self.UTXO_AI_ENDPOINTS.map(({ label, installUrl }) => ({ label, installUrl })),
      bridgeUrl: DEFAULT_STATE.settings.bridgeUrl,
      licenseUrl: DEFAULT_LICENSE_URL,
      productId: PRODUCT_ID,
    });
    return true;
  }
});

