/**
 * 在本機（有螢幕）登入 Threads，並把 Playwright storageState 傳到遠端 server。
 *
 * 用法：
 *   SERVER_URL=https://your-server.com \
 *   HAIXUN_SESSION=你的haixun_session_cookie值 \
 *   npm run threads:login-local
 *
 * HAIXUN_SESSION：在瀏覽器登入巡樓後，從 DevTools → Application → Cookies 複製 haixun_session。
 */

import { chromium } from "playwright";
import { assessComposeReady, dismissBlockingDialogs } from "../lib/threads-browser/compose";

const LOGIN_URL = "https://www.threads.com/login";
const HOME_URL = "https://www.threads.com/";
const SESSION_COOKIE = "haixun_session";

async function extractUsername(page: import("playwright").Page): Promise<string | null> {
  try {
    const profileLink = page.locator('a[href*="/@"]').first();
    const href = await profileLink.getAttribute("href", { timeout: 5000 });
    if (!href) return null;
    const match = href.match(/@([^/?]+)/);
    return match?.[1] ?? null;
  } catch {
    return null;
  }
}

async function loginLocally(): Promise<{ storageState: string; username: string | null }> {
  const browser = await chromium.launch({
    headless: false,
    args: ["--disable-blink-features=AutomationControlled"],
  });

  try {
    const context = await browser.newContext({
      userAgent:
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    });
    const page = await context.newPage();

    console.log("請在彈出的瀏覽器完成 Threads / Instagram 登入…");
    await page.goto(LOGIN_URL, { waitUntil: "domcontentloaded", timeout: 60000 });

    try {
      await page.waitForURL(
        (url) =>
          url.hostname.includes("threads") &&
          !url.pathname.includes("/login") &&
          !url.hostname.includes("instagram"),
        { timeout: 300000 }
      );
    } catch {
      // 可能停在 Instagram 授權頁
    }

    const deadline = Date.now() + 300000;
    let compose = await assessComposeReady(page);
    while (!compose.ready && Date.now() < deadline) {
      if (page.url().includes("instagram.com")) {
        await page.waitForTimeout(2000);
      } else {
        await page.goto(HOME_URL, { waitUntil: "domcontentloaded", timeout: 45000 }).catch(() => undefined);
        await page.waitForTimeout(2000);
        await dismissBlockingDialogs(page);
        compose = await assessComposeReady(page);
      }
      if (!compose.ready) await page.waitForTimeout(2000);
    }

    if (!compose.ready) {
      throw new Error(
        compose.message ??
          "登入逾時。請確認已在瀏覽器完成 Instagram 授權，並看見 Threads 首頁。"
      );
    }

    await dismissBlockingDialogs(page);
    const username = await extractUsername(page);
    const storageState = JSON.stringify(await context.storageState());
    return { storageState, username };
  } finally {
    await browser.close();
  }
}

async function importToServer(
  serverUrl: string,
  sessionToken: string,
  storageState: string
): Promise<{ success: boolean; valid: boolean; username?: string | null; message: string }> {
  const url = `${serverUrl.replace(/\/$/, "")}/api/session/import`;
  const res = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Cookie: `${SESSION_COOKIE}=${sessionToken}`,
    },
    body: JSON.stringify({ storageState }),
  });

  const data = (await res.json()) as {
    success?: boolean;
    valid?: boolean;
    username?: string | null;
    message?: string;
    error?: string;
  };

  if (!res.ok) {
    throw new Error(data.error ?? data.message ?? `匯入失敗（HTTP ${res.status}）`);
  }

  return {
    success: data.success ?? false,
    valid: data.valid ?? false,
    username: data.username,
    message: data.message ?? "已匯入",
  };
}

async function main() {
  const serverUrl = process.env.SERVER_URL?.trim();
  const sessionToken = process.env.HAIXUN_SESSION?.trim();

  if (!serverUrl) {
    console.error("請設定 SERVER_URL，例如：https://your-linux-server.com");
    process.exit(1);
  }

  if (!sessionToken) {
    console.error(
      "請設定 HAIXUN_SESSION（瀏覽器登入巡樓後，從 Cookies 複製 haixun_session 的值）"
    );
    process.exit(1);
  }

  const { storageState, username } = await loginLocally();
  console.log(username ? `本機登入成功：@${username}` : "本機登入成功");

  console.log(`正在傳送到 ${serverUrl}…`);
  const result = await importToServer(serverUrl, sessionToken, storageState);

  if (result.valid) {
    console.log(
      `✓ Server session 有效${result.username ? ` · @${result.username}` : ""} — ${result.message}`
    );
    process.exit(0);
  }

  console.error(`✗ Session 已傳送但驗證失敗：${result.message}`);
  process.exit(1);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : error);
  process.exit(1);
});