import express from "express";
import multer from "multer";
import fs from "fs";
import path from "path";

const app = express();
const PORT = process.env.PORT || 3000;

// Static files (ensure your build uses public dir)
const PUBLIC_DIR = path.join(process.cwd(), "public");
const MANIFEST_PATH = path.join(PUBLIC_DIR, "site", "data", "manifest.logo.json");
const SRC_DIR = path.join(PUBLIC_DIR, "templates", "logo", "source");
const PREV_DIR = path.join(PUBLIC_DIR, "templates", "logo", "previews");

[PUBLIC_DIR, path.dirname(MANIFEST_PATH), SRC_DIR, PREV_DIR].forEach(p => {
  if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
});

app.use(express.static(PUBLIC_DIR, { fallthrough: true }));

const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 }});

app.post("/api/logo-templates/upload", upload.fields([
  { name: "svg", maxCount: 1 },
  { name: "preview", maxCount: 1 },
]), (req, res) => {
  try {
    const id = String(req.body.id || "").trim();
    const name = String(req.body.name || "").trim();
    const brandName = String(req.body.brandName || "");
    const tagline = String(req.body.tagline || "");
    const estYear = String(req.body.estYear || "");
    const primary = String(req.body.primary || "#231f20");
    const secondary = String(req.body.secondary || "#978752");
    const accent = String(req.body.accent || "#6dc282");
    const tags = String(req.body.tags || "").split(",").map(s=>s.trim()).filter(Boolean);

    if (!id || !/^[a-z0-9\-]+$/.test(id)) return res.status(400).json({ error: "Invalid id (use kebab-case letters/numbers)" });
    if (!name) return res.status(400).json({ error: "Name is required" });

    const svgFile = (req.files as any)?.svg?.[0];
    const previewFile = (req.files as any)?.preview?.[0];
    if (!svgFile) return res.status(400).json({ error: "SVG file is required" });
    if (!previewFile) return res.status(400).json({ error: "Preview file is required" });

    const svgText = svgFile.buffer.toString("utf-8");
    const tokenIssues: string[] = [];
    ["{Brand_Name}", "{Tagline}", "{Est_Year}"].forEach(tok => {
      if (!svgText.includes(tok)) tokenIssues.push(`Missing ${tok}`);
    });
    ["--primary","--secondary","--accent"].forEach(v => {
      if (!svgText.includes(v)) tokenIssues.push(`Missing ${v}`);
    });
    if (!/^\s*<svg[\s\S]*<\/svg>\s*$/i.test(svgText)) tokenIssues.push("Not a valid <svg>…</svg>");

    if (tokenIssues.length) {
      return res.status(400).json({ error: "SVG validation failed", details: tokenIssues });
    }

    // Save SVG
    const svgOut = path.join(SRC_DIR, `${id}.svg`);
    fs.writeFileSync(svgOut, svgFile.buffer);

    // Save Preview
    const ext = previewFile.mimetype === "image/png" ? "png" : "jpg";
    const prevOut = path.join(PREV_DIR, `${id}.${ext}`);
    fs.writeFileSync(prevOut, previewFile.buffer);

    // Load or init manifest
    let manifest: any = { collection: "logo", version: 1, items: [] as any[] };
    if (fs.existsSync(MANIFEST_PATH)) {
      try { manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, "utf-8")); } catch {}
    }
    manifest.collection = "logo";
    manifest.version = Number(manifest.version || 1);

    const previewUrl = `/templates/logo/previews/${id}.${ext}`;
    const svgUrl = `/templates/logo/source/${id}.svg`;

    const item = {
      id,
      name,
      previewUrl,
      svgUrl,
      defaultFields: {
        Brand_Name: brandName,
        Tagline: tagline,
        Est_Year: estYear
      },
      fieldOrder: ["Brand_Name", "Tagline", "Est_Year"],
      defaultColors: { primary, secondary, accent },
      tags
    };

    const idx = (manifest.items || []).findIndex((x:any)=>x.id===id);
    if (idx >= 0) {
      manifest.items[idx] = item;
    } else {
      manifest.items.push(item);
    }

    fs.writeFileSync(MANIFEST_PATH, JSON.stringify(manifest, null, 2));
    return res.json({ ok: true, item });
  } catch (e:any) {
    console.error(e);
    return res.status(500).json({ error: "Server error", detail: String(e?.message || e) });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
