/**
 * Live check of the full-poster image path against real stored project data.
 *
 *   npx tsx scripts/test-logo-poster.ts                 # active project
 *   npx tsx scripts/test-logo-poster.ts "Gventure"      # match by name
 *
 * Reports which path the chain took (logo-reference poster, plain full banner,
 * or SVG composite fallback) and saves the rendered PNG for review.
 */
import { promises as fs, readFileSync } from "fs";
import path from "path";
import { runImageProviderChain } from "../src/lib/ai/image-provider-chain";
import { applyLogoOverlayToImageFile } from "../src/lib/generation/logo-overlay";
import { buildSocialImageContext } from "../src/lib/generation/social-image";
import type { BrandProfile, PostSequenceItem, Project } from "../src/types/workflow";

/** Minimal .env.local reader — avoids adding a dotenv dependency for one script. */
function loadEnvLocal(): void {
  let text = "";
  try {
    text = readFileSync(".env.local", "utf-8");
  } catch {
    return;
  }
  for (const line of text.split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const eq = trimmed.indexOf("=");
    if (eq <= 0) continue;
    const key = trimmed.slice(0, eq).trim();
    const value = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, "");
    if (!(key in process.env)) process.env[key] = value;
  }
}

loadEnvLocal();

const OUT_DIR = path.join(process.cwd(), "data", "media", "_preview");

interface ProjectsFile {
  activeProjectId?: string;
  projects?: Project[];
  dataByProjectId?: Record<string, { brand?: BrandProfile }>;
}

async function main() {
  await fs.mkdir(OUT_DIR, { recursive: true });

  const store = JSON.parse(
    await fs.readFile("data/users/demo_user/projects.json", "utf-8"),
  ) as ProjectsFile;

  const wanted = process.argv[2]?.toLowerCase();
  const projects = store.projects ?? [];
  const project =
    (wanted
      ? projects.find((p) => p.name?.toLowerCase().includes(wanted))
      : projects.find((p) => p.id === store.activeProjectId)) ?? projects[0];

  if (!project) {
    console.error("No project found.");
    process.exit(1);
  }

  const brand = (store.dataByProjectId?.[project.id]?.brand ?? {}) as BrandProfile;

  console.log(`Project:        ${project.name}`);
  console.log(`Logo uploaded:  ${Boolean(brand.logoDataUrl)}`);
  console.log(`Contact phone:  ${brand.contactPhone || "(none)"}`);
  console.log(`Contact email:  ${brand.contactEmail || "(none)"}`);

  const sequenceItem: PostSequenceItem = {
    id: "seq-1",
    title: "Post 1 — Intelligent Routing",
    summary: "Missed routes cost revenue",
    tag: "Awareness",
    content: "Calls sent to the wrong destination can cost your business money.",
  };

  const ctx = buildSocialImageContext({
    project,
    brand,
    sequenceItem,
    caption:
      "**Every Missed Route Is Lost Revenue** — calls sent to the wrong destination cost you money.",
    storySections: {
      currentStory: "",
      keyTheme: "Intelligent routing",
      problem: "Calls sent to the wrong destination can cost your business money.",
      impact: "Better distribution, faster connections, higher conversion potential.",
      brandResponse: "Route smarter. Earn more.",
    },
    layoutSeed: 42,
  });

  ctx.postBannerContent = {
    headline: "Every Missed Route Is Lost Revenue",
    subheadline: "Calls sent to the wrong destination can cost your business money.",
    features: [
      { label: "Better Distribution", detail: "Get calls to the right team.", icon: "service", accent: false },
      { label: "Faster Connections", detail: "Reduce wait time.", icon: "solution", accent: true },
      { label: "Higher Conversion Potential", detail: "Turn more calls into customers.", icon: "impact", accent: false },
    ],
    ctaSubline: "Route smarter. Earn more.",
    visualHook: "Intelligent call routing to the right department",
  };

  console.log("\nRequesting image (up to ~60s)...");
  const started = Date.now();
  const result = await runImageProviderChain("", ctx);
  const elapsed = ((Date.now() - started) / 1000).toFixed(1);

  console.log(`\nprovider:     ${result.provider}`);
  console.log(`imageModel:   ${result.imageModel}`);
  console.log(`chain:        ${result.providerChain}`);
  console.log(`warning:      ${result.warning ?? "none"}`);
  console.log(`svgTemplate:  ${result.brandTemplateComposed ? "YES (fallback)" : "no (full AI poster)"}`);
  console.log(`elapsed:      ${elapsed}s`);

  const url = result.imageUrl;
  let buf: Buffer | null = null;
  if (url.startsWith("data:image/svg")) {
    console.log("\nResult is the SVG template, not a raster poster.");
  } else if (url.startsWith("data:image")) {
    const m = url.match(/^data:([^;]+);base64,(.+)$/);
    if (m) buf = Buffer.from(m[2]!, "base64");
  } else if (url.startsWith("http")) {
    const res = await fetch(url);
    buf = Buffer.from(await res.arrayBuffer());
  }

  if (buf) {
    const slug = (project.name || "project").toLowerCase().replace(/[^a-z0-9]+/g, "-");
    const out = path.join(OUT_DIR, `poster-${slug}.png`);
    await fs.writeFile(out, buf);

    // Mirror run-generation: stamp the exact logo into the corner the generator
    // reserved, so the preview shows the same composite the user receives.
    const placement = result.logoPlacement ?? "top_right";
    console.log(`logoPlacement: ${placement}`);
    if (result.logoAlreadyRendered) {
      console.log("logoStamp:     skipped (already in image)");
    } else {
      const stamped = await applyLogoOverlayToImageFile({
        imagePath: out,
        logoDataUrl: brand.logoDataUrl ?? null,
        postId: `preview-${slug}`,
        logoPlacement: placement,
        wipeColor: ctx.primaryColor || ctx.brandStyle.primaryColor,
      });
      console.log(
        `logoStamp:     ${stamped.ok ? "applied" : `skipped (${stamped.error ?? "unknown"})`}`,
      );
    }
    console.log(`saved:        ${out}`);
  }
}

void main();
