import "dotenv/config";
import express from "express";
import cors from "cors";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { initDatabase } from "./database.js";
import { sessionRoutes } from "./routes/session.js";
import { analyticsRoutes } from "./routes/analytics.js";
import { Flow, parseAndValidate } from "./types/flow.js";

const PORT = Number(process.env.PORT ?? 3100);
const FLOW_PATH = process.env.FLOW_PATH ?? "./flow.json";
const CORS_ORIGIN = (process.env.CORS_ORIGIN ?? "*")
  .split(",")
  .map((s) => s.trim());

// ─── Carrega e valida flow.json no startup ──────────────────
function loadFlow(): Flow {
  const raw = readFileSync(resolve(FLOW_PATH), "utf-8");
  const json = JSON.parse(raw);
  const result = parseAndValidate(json);

  if (!result.ok || !result.flow) {
    console.error("❌ flow.json invalido. Issues:");
    result.issues.forEach((i) =>
      console.error(`  [${i.level}] ${i.block_id ?? "global"}: ${i.message}`),
    );
    process.exit(1);
  }

  const warnings = result.issues.filter((i) => i.level === "warning");
  if (warnings.length > 0) {
    console.warn(`⚠️  ${warnings.length} aviso(s) no flow.json (nao bloqueante):`);
    warnings.forEach((i) =>
      console.warn(`  ${i.block_id ?? "global"}: ${i.message}`),
    );
  }

  return result.flow;
}

const flow = loadFlow();
const db = initDatabase();

// ─── Express ────────────────────────────────────────────────
const app = express();
app.use(cors({ origin: CORS_ORIGIN }));
app.use(express.json({ limit: "1mb" }));

app.get("/api/health", (_req, res) => {
  res.json({
    ok: true,
    bot: flow.bot_name,
    slug: flow.bot_slug,
    archetype: flow.archetype,
    blocks: Object.keys(flow.blocks).length,
  });
});

app.get("/api/flow/meta", (_req, res) => {
  res.json({
    bot_name: flow.bot_name,
    bot_slug: flow.bot_slug,
    archetype: flow.archetype,
    theme: flow.theme,
  });
});

app.use("/api/session", sessionRoutes(flow, db));
app.use("/api/analytics", analyticsRoutes(db));

app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
  console.error("[error]", err);
  res.status(500).json({ error: "internal_error", message: err.message });
});

app.listen(PORT, () => {
  console.log(`🤖 Imperatriz Bot "${flow.bot_name}" rodando em http://localhost:${PORT}`);
  console.log(`   Arquetipo: ${flow.archetype} · ${Object.keys(flow.blocks).length} blocos`);
  console.log(`   Slug: ${flow.bot_slug}`);
});
