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("; ");
  console.log("login", login.status, "cookie?", Boolean(cookie));

  const projRes = await fetch(`${base}/api/projects`, { headers: { Cookie: cookie } });
  const { snapshot } = (await projRes.json()) as {
    snapshot: {
      activeProjectId: string;
      projects: Array<{ id: string; name?: string }>;
      dataByProjectId: Record<string, any>;
    };
  };
  const pid = snapshot.activeProjectId;
  const scoped = snapshot.dataByProjectId[pid];
  const project = snapshot.projects.find((p) => p.id === pid);
  console.log(
    "Active project:",
    project?.name,
    "logo?",
    Boolean(scoped.brand?.logoDataUrl && scoped.brand.logoDataUrl.length > 100),
  );

  // Prefer a real PNG brand mark for verification when none is stored.
  let verifyLogo =
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mNk+M9Qz0AEYBxVSF+FABJADveWkH6oAAAAAElFTkSuQmCC";
  try {
    const { promises: fsp } = await import("fs");
    const pathMod = await import("path");
    const logoPath = pathMod.join(process.cwd(), "data", "media", "_brand-logo.png");
    const buf = await fsp.readFile(logoPath);
    verifyLogo = `data:image/png;base64,${buf.toString("base64")}`;
  } catch {
    /* keep tiny fallback */
  }
  const brand = {
    ...scoped.brand,
    logoDataUrl: scoped.brand?.logoDataUrl?.trim() || verifyLogo,
    logoFileName: scoped.brand?.logoFileName || "verify-logo.png",
  };

  scoped.context = scoped.context ?? {};
  scoped.context.businessContext = {
    ...(scoped.context.businessContext ?? {}),
    companyName: scoped.brand?.companyName || "B2BEFAX",
    description: scoped.brand?.tagline || "Fax campaign management",
    industry: scoped.brand?.industry || "Technology",
    products: ["Online Fax"],
    services: ["Fax campaign management"],
    features: [],
    audience: "Businesses",
    locations: ["US"],
    customerProblems: ["Unreliable document delivery"],
    painPoints: ["Manual fax"],
    businessImpact: ["Delayed approvals"],
    differentiators: [],
    benefits: [],
    useCases: [],
    websiteClaims: [],
    verifiedClaims: [],
    missingInformation: [],
    contact: {
      phone: scoped.brand?.contactPhone || "+1(808)830-3232",
      email: scoped.brand?.contactEmail || "hello@b2befax.com",
      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",
        summary: "Impact",
        tag: "Impact",
        content: "Problem: unreliable document delivery.\nImpact: delayed approvals.\n#B2B",
      },
    ];
  }

  console.log("Generating (image+video)...");
  const genRes = await fetch(`${base}/api/generation/generate`, {
    method: "POST",
    headers: { "Content-Type": "application/json", Cookie: cookie },
    body: JSON.stringify({
      projectId: pid,
      project,
      brand,
      context: scoped.context,
      sequencePostId: scoped.context.posts[0].id,
      connectedPlatforms: ["linkedin", "youtube"],
      schedule: scoped.schedule,
      automation: scoped.automation,
      accounts: scoped.accounts,
      mode: "specific",
    }),
  });
  const gen = await genRes.json();
  const post = gen.post;
  console.log("HTTP", genRes.status);
  if (!post) {
    console.log("FAIL", JSON.stringify(gen).slice(0, 800));
    process.exit(1);
  }
  console.log(
    JSON.stringify(
      {
        id: post.id,
        imageUrl: String(post.imageUrl || "").slice(0, 100),
        videoStatus: post.videoStatus,
        videoUrl: String(post.videoUrl || "").slice(0, 100),
        videoWarning: post.videoWarning,
        videoSlideCount: post.videoSlideCount,
        imageModel: post.imageModel || post.aiMeta?.imageModel,
        captionLen: (post.caption || "").length,
      },
      null,
      2,
    ),
  );
  const asset = String(post.imageUrl || "").match(/\/api\/media\/([^.?]+)/)?.[1];
  if (asset) {
    const { promises: fs } = await import("fs");
    const path = await import("path");
    const media = path.join(process.cwd(), "data", "media");
    const slides = [];
    for (let i = 0; i < 5; i++) {
      try {
        await fs.access(path.join(media, `${asset}-slide-${i}.png`));
        slides.push(i);
      } catch {
        /* missing */
      }
    }
    console.log("slide pngs:", slides.length, slides);
  }
  if (post.videoStatus === "failed") process.exit(2);
}

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