/**
 * Quick OpenAI generation smoke test.
 * Usage: npx tsx scripts/test-openai-generate.ts [baseUrl]
 */
const base = process.argv[2] ?? "http://127.0.0.1:3058";

async function main() {
  const login = await fetch(`${base}/api/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: "sarah@postsync.pro", password: "demo" }),
  });
  const cookie = (login.headers.getSetCookie?.() ?? [])
    .map((c) => c.split(";")[0])
    .join("; ");

  const cfgRes = await fetch(`${base}/api/ai/config`, { headers: { Cookie: cookie } });
  const cfg = await cfgRes.json();
  console.log("AI config:", JSON.stringify(cfg));

  if (cfg.provider !== "openai") {
    console.log("FAIL expected AI_PROVIDER=openai, got", cfg.provider);
    process.exit(1);
  }

  const projRes = await fetch(`${base}/api/projects`, { headers: { Cookie: cookie } });
  const { snapshot } = (await projRes.json()) as {
    snapshot: {
      activeProjectId: string;
      projects: Array<Record<string, unknown>>;
      dataByProjectId: Record<string, any>;
    };
  };
  const pid = snapshot.activeProjectId;
  const scoped = snapshot.dataByProjectId[pid];
  const project = snapshot.projects.find((p) => p.id === pid);

  scoped.context = scoped.context ?? {};
  scoped.context.businessContext = {
    ...(scoped.context.businessContext ?? {}),
    companyName: scoped.brand?.companyName || "Gventure Technology",
    description: scoped.brand?.tagline || "Technology",
    industry: scoped.brand?.industry || "Software",
    products: ["Online Fax", "VoIP"],
    services: ["Online faxing", "bulk fax", "VoIP"],
    features: [],
    audience: scoped.brand?.targetAudience || "Businesses",
    locations: ["Global"],
    customerProblems: ["Unreliable document delivery"],
    painPoints: ["Manual fax workflows"],
    businessImpact: ["Delayed approvals"],
    differentiators: [],
    benefits: [],
    useCases: [],
    websiteClaims: [],
    verifiedClaims: [],
    missingInformation: [],
    contact: {
      phone: scoped.brand?.contactPhone || "missing",
      email: scoped.brand?.contactEmail || "missing",
      address: "missing",
    },
    fieldSources: {},
    confirmed: true,
    confirmedAt: new Date().toISOString(),
  };
  scoped.context.saved = true;
  if (!Array.isArray(scoped.context.posts) || !scoped.context.posts.length) {
    scoped.context.posts = [
      {
        id: "seq-1",
        title: "Impact of the problem",
        summary: "Business impact",
        tag: "Impact",
        content:
          "Problem: high-volume secure document communication fails across healthcare and legal teams.\nImpact: delayed approvals and compliance risk.\n#B2B",
      },
    ];
  }

  const genRes = await fetch(`${base}/api/generation/generate`, {
    method: "POST",
    headers: { "Content-Type": "application/json", Cookie: cookie },
    body: JSON.stringify({
      projectId: pid,
      project,
      brand: scoped.brand,
      context: scoped.context,
      sequencePostId: scoped.context.posts[0].id,
      connectedPlatforms: ["linkedin"],
      schedule: scoped.schedule,
      automation: scoped.automation,
      accounts: scoped.accounts,
      mode: "specific",
    }),
  });
  const gen = await genRes.json();
  console.log("GEN status:", genRes.status);
  if (gen.post?.id) {
    console.log("PASS OpenAI generate", gen.post.id, "captionLen", (gen.post.caption ?? "").length);
    process.exit(0);
  }
  console.log("FAIL", JSON.stringify(gen).slice(0, 400));
  process.exit(1);
}

main().catch((e) => {
  console.error(e);
  process.exit(2);
});
