import type { Hono } from "hono";
import { z } from "zod";
import type { WsBridge } from "../ws-bridge.js";
import { getSettings, updateSettings } from "../settings-manager.js";
import { runQualityGate } from "../quality-gate.js";
import type { QualityGateConfig } from "../quality-gate.js";
import { parseBody } from "../validation.js";
import { createLogger } from "../logger.js";

const log = createLogger("quality-gate-routes");

// ─── Zod Schemas ──────────────────────────────────────────────────

const qualityGateCheckSchema = z.object({
  name: z.string().min(1).max(100),
  command: z.string().min(1).max(2000),
  enabled: z.boolean(),
  timeoutSeconds: z.number().int().min(5).max(600),
});

const qualityGateConfigSchema = z.object({
  enabled: z.boolean(),
  checks: z.array(qualityGateCheckSchema).min(0).max(20),
});

// ─── Dependencies ─────────────────────────────────────────────────

export interface QualityGateRouteDeps {
  wsBridge: WsBridge;
}

// ─── Route Registration ───────────────────────────────────────────

export function registerQualityGateRoutes(api: Hono, deps: QualityGateRouteDeps): void {
  const { wsBridge } = deps;

  /** GET /quality-gate/config — read current quality gate settings */
  api.get("/quality-gate/config", (c) => {
    const settings = getSettings();
    return c.json(settings.qualityGate);
  });

  /** PUT /quality-gate/config — update quality gate settings */
  api.put("/quality-gate/config", async (c) => {
    const parsed = await parseBody(c, qualityGateConfigSchema);
    if (!parsed.success) return parsed.response;

    const updated = updateSettings({ qualityGate: parsed.data as QualityGateConfig });
    return c.json(updated.qualityGate);
  });

  /** POST /sessions/:id/quality-gate — run quality gate for a session */
  api.post("/sessions/:id/quality-gate", async (c) => {
    const sessionId = c.req.param("id");
    const session = wsBridge.getSession(sessionId);

    if (!session) {
      return c.json({ error: "Session not found" }, 404);
    }

    const cwd = session.state.cwd;
    if (!cwd) {
      return c.json({ error: "Session has no working directory" }, 400);
    }

    const settings = getSettings();
    const qualityGateConfig = settings.qualityGate;

    if (!qualityGateConfig.enabled) {
      return c.json({ error: "Quality gate is not enabled" }, 400);
    }

    log.info({ sessionId, cwd }, "Running quality gate for session");
    const result = await runQualityGate(cwd, qualityGateConfig);

    return c.json(result);
  });
}
