import fs from "node:fs";
import { DEFAULT_RPA_STORAGE_STATE_PATH } from "@/lib/rpa/env";
import { hasEffectiveMothershipLogin } from "@/lib/rpa/mothership-login-context";

export type PlaywrightStorageState = {
  cookies: Array<{
    name: string;
    value: string;
    domain?: string;
  }>;
};

export const DEFAULT_LOGGED_IN_STORAGE_STATE_PATH =
  ".rpa/mothership-logged-in-storage.json";

export function resolveStorageStatePath(): string {
  const loggedInPath =
    process.env.RPA_LOGGED_IN_STORAGE_STATE_PATH?.trim() ||
    DEFAULT_LOGGED_IN_STORAGE_STATE_PATH;
  // 有 MotherShip 账密时优先登录态 cookie，价源对齐 dashboard
  if (hasEffectiveMothershipLogin() && fs.existsSync(loggedInPath)) {
    return loggedInPath;
  }
  return (
    process.env.RPA_STORAGE_STATE_PATH?.trim() || DEFAULT_RPA_STORAGE_STATE_PATH
  );
}

export function loadStorageState(
  path = resolveStorageStatePath(),
): PlaywrightStorageState {
  if (!fs.existsSync(path)) {
    throw new Error(
      `缺少 MotherShip 会话文件 ${path}；系统将尝试自动获取，或运行 npm run record:mothership`,
    );
  }
  return JSON.parse(fs.readFileSync(path, "utf8")) as PlaywrightStorageState;
}

/** 缺会话时自动 bootstrap，再读取 storageState */
export async function loadStorageStateAsync(
  path = resolveStorageStatePath(),
): Promise<PlaywrightStorageState> {
  const { ensureMothershipStorageState } = await import(
    "@/lib/rpa/ensure-storage-state"
  );
  await ensureMothershipStorageState();
  return loadStorageState(path);
}

export function buildCookieHeader(state: PlaywrightStorageState): string {
  return state.cookies.map((c) => `${c.name}=${c.value}`).join("; ");
}
