import { NextResponse } from "next/server";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { DEFAULT_BRAND, type Brand, type Typeface, type Appearance, type PageBg, type Density, type DisplayFace } from "@/lib/theme/brand";

// Dev-only writer for lib/theme/brand.ts. The /components configurator POSTs here
// on "Apply" ({ seed, typeface, appearance }) and "Reset" ({ reset: true }). It
// rewrites just the brand block; editing the file triggers Fast Refresh, so the
// whole app re-themes. NOT available in production builds.

const FILE = join(process.cwd(), "lib", "theme", "brand.ts");
const BLOCK = /export const brand: Brand = \{[\s\S]*?\};/;
const TYPEFACES: Typeface[] = ["inter", "geist", "general"];
const APPEARANCES: Appearance[] = ["light", "dark"];
const PAGE_BGS: PageBg[] = ["seed", "contrast", "custom"];
const DENSITIES: Density[] = ["comfortable", "compact"];
const DISPLAY_FACES: DisplayFace[] = ["match", "serif"];

function isBrand(b: unknown): b is Brand {
  const x = b as Brand;
  return (
    !!x &&
    typeof x.seed === "string" &&
    /^#[0-9a-fA-F]{6}$/.test(x.seed) &&
    TYPEFACES.includes(x.typeface) &&
    APPEARANCES.includes(x.appearance) &&
    typeof x.cornerSmoothing === "boolean" &&
    typeof x.fullRounded === "boolean" &&
    PAGE_BGS.includes(x.pageBg) &&
    DENSITIES.includes(x.density) &&
    DISPLAY_FACES.includes(x.displayFace) &&
    typeof x.pageBgCustom === "string" &&
    /^#[0-9a-fA-F]{6}$/.test(x.pageBgCustom)
  );
}

export async function POST(req: Request) {
  if (process.env.NODE_ENV !== "development") {
    return NextResponse.json({ error: "The configurator only writes in dev." }, { status: 403 });
  }
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Bad JSON" }, { status: 400 });
  }
  const next: Brand = (body as { reset?: boolean })?.reset ? DEFAULT_BRAND : (body as Brand);
  if (!isBrand(next)) {
    return NextResponse.json({ error: "Invalid brand (need #rrggbb seed, known typeface, light|dark)." }, { status: 400 });
  }
  const block = `export const brand: Brand = {\n  seed: "${next.seed}",\n  typeface: "${next.typeface}",\n  appearance: "${next.appearance}",\n  cornerSmoothing: ${next.cornerSmoothing},\n  fullRounded: ${next.fullRounded},\n  pageBg: "${next.pageBg}",\n  pageBgCustom: "${next.pageBgCustom}",\n  density: "${next.density}",\n  displayFace: "${next.displayFace}",\n};`;
  try {
    const src = await readFile(FILE, "utf8");
    if (!BLOCK.test(src)) {
      return NextResponse.json({ error: "Could not find the brand block in lib/theme/brand.ts" }, { status: 500 });
    }
    await writeFile(FILE, src.replace(BLOCK, block), "utf8");
    return NextResponse.json({ ok: true, brand: next });
  } catch (e) {
    return NextResponse.json({ error: String(e) }, { status: 500 });
  }
}
