import playwright from "playwright";
import { readFileSync, existsSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));

let sharedBrowser = null;
let sharedContext = null;
let sharedPage = null;

async function getSharedPage() {
  if (sharedPage && !sharedPage.isClosed()) {
    return sharedPage;
  }
  
  try {
    sharedBrowser = await playwright.chromium.launch({
      headless: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-blink-features=AutomationControlled",
      ]
    });

    let dynamicUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
    let cfCookies = [];
    try {
      const sessionPath = join(__dirname, "../cloudflare/session.json");
      if (existsSync(sessionPath)) {
        const sessionData = JSON.parse(readFileSync(sessionPath, "utf8"));
        if (sessionData && sessionData.userAgent) {
          dynamicUserAgent = sessionData.userAgent;
        }
        if (sessionData && sessionData.cookies) {
          cfCookies = sessionData.cookies.map(c => ({
            name: c.name,
            value: c.value,
            domain: c.domain,
            path: c.path,
            expires: c.expires || -1,
            httpOnly: c.httpOnly || false,
            secure: c.secure || false,
            sameSite: c.sameSite || "Lax"
          }));
        }
      }
    } catch (_) {}

    sharedContext = await sharedBrowser.newContext({
      userAgent: dynamicUserAgent,
      viewport: { width: 1280, height: 720 }
    });

    if (cfCookies.length) {
      await sharedContext.addCookies(cfCookies);
    }

    sharedPage = await sharedContext.newPage();

    // Inject route interceptor to inject cf_clearance cookie to api.weavy.ai
    try {
      const sessionPath = join(__dirname, "../cloudflare/session.json");
      if (existsSync(sessionPath)) {
        const sessionData = JSON.parse(readFileSync(sessionPath, "utf8"));
        if (sessionData && sessionData.cookieString) {
          const cfCookieString = sessionData.cookieString;
          await sharedPage.route("https://api.weavy.ai/**", async (route) => {
            const req = route.request();
            const currentHeaders = req.headers();
            let newCookie = cfCookieString;
            if (currentHeaders["cookie"]) {
              newCookie = `${currentHeaders["cookie"]}; ${cfCookieString}`;
            }
            await route.continue({
              headers: {
                ...currentHeaders,
                "cookie": newCookie
              }
            });
          });
        }
      }
    } catch (_) {}

    await sharedPage.goto("https://app.weavy.ai/signin", { waitUntil: "domcontentloaded", timeout: 15000 }).catch(() => {});
    
    return sharedPage;
  } catch (err) {
    console.error("[WeavyClient] Gagal inisialisasi Playwright Weavy Page:", err.message);
    return null;
  }
}

export async function browserWeavyFetch(url, options = {}) {
  const page = await getSharedPage();
  if (!page) {
    console.warn("[WeavyClient] Playwright page tidak tersedia, fallback ke direct Node fetch");
    return fetch(url, options);
  }

  try {
    const result = await page.evaluate(async ({ url, options }) => {
      try {
        const response = await fetch(url, options);
        const status = response.status;
        const ok = response.ok;
        const text = await response.text();
        return { ok, status, text };
      } catch (err) {
        return { ok: false, status: 0, text: err.message };
      }
    }, { url, options });

    return {
      ok: result.ok,
      status: result.status,
      text: async () => result.text,
      json: async () => JSON.parse(result.text),
    };
  } catch (err) {
    console.error("[WeavyClient] browserWeavyFetch error, merestart browser page:", err.message);
    sharedPage = null;
    return fetch(url, options);
  }
}
