import type { Hono } from "hono";
import { z } from "zod";
import { DEFAULT_OPENROUTER_MODEL, getSettings, updateSettings } from "../settings-manager.js";
import { linearCache } from "../linear-cache.js";
import { parseBody } from "../validation.js";

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

const settingsUpdateSchema = z.object({
  openrouterApiKey: z.string().max(500).optional(),
  openrouterModel: z.string().max(200).optional(),
  linearApiKey: z.string().max(500).optional(),
  linearAutoTransition: z.boolean().optional(),
  linearAutoTransitionStateId: z.string().max(200).optional(),
  linearAutoTransitionStateName: z.string().max(200).optional(),
  editorTabEnabled: z.boolean().optional(),
  attribution: z.boolean().optional(),
  sessionDefaults: z.object({
    model: z.string().max(200).optional().nullable(),
    permissionMode: z.string().max(100).optional().nullable(),
    enableFileCheckpointing: z.boolean().optional().nullable(),
    maxTurns: z.number().int().min(1).max(10000).optional().nullable(),
    maxBudgetUsd: z.number().min(0.01).max(1000).optional().nullable(),
    systemPrompt: z.string().max(50000).optional().nullable(),
    appendSystemPrompt: z.string().max(50000).optional().nullable(),
    thinking: z.discriminatedUnion("type", [
      z.object({ type: z.literal("adaptive") }),
      z.object({ type: z.literal("enabled"), budgetTokens: z.number().int().min(1024).max(128000) }),
      z.object({ type: z.literal("disabled") }),
    ]).optional().nullable(),
    effort: z.enum(["low", "medium", "high", "max"]).optional().nullable(),
    disallowedTools: z.array(z.string().max(200)).max(50).optional().nullable(),
    additionalDirectories: z.array(z.string().max(1000)).max(20).optional().nullable(),
    betas: z.array(z.string().max(100)).max(10).optional().nullable(),
  }).optional(),
}).refine(
  (data) => Object.values(data).some((v) => v !== undefined),
  { message: "At least one settings field is required" },
);

export function registerSettingsRoutes(api: Hono): void {
  api.get("/settings", (c) => {
    const settings = getSettings();
    return c.json({
      openrouterApiKeyConfigured: !!settings.openrouterApiKey.trim(),
      openrouterModel: settings.openrouterModel || DEFAULT_OPENROUTER_MODEL,
      linearApiKeyConfigured: !!settings.linearApiKey.trim(),
      linearAutoTransition: settings.linearAutoTransition,
      linearAutoTransitionStateName: settings.linearAutoTransitionStateName,
      editorTabEnabled: settings.editorTabEnabled,
      attribution: settings.attribution,
      sessionDefaults: settings.sessionDefaults,
    });
  });

  api.put("/settings", async (c) => {
    const parsed = await parseBody(c, settingsUpdateSchema);
    if (!parsed.success) return parsed.response;
    const body = parsed.data;

    if (typeof body.linearApiKey === "string") {
      linearCache.clear();
    }

    const settings = updateSettings({
      openrouterApiKey:
        typeof body.openrouterApiKey === "string"
          ? body.openrouterApiKey.trim()
          : undefined,
      openrouterModel:
        typeof body.openrouterModel === "string"
          ? (body.openrouterModel.trim() || DEFAULT_OPENROUTER_MODEL)
          : undefined,
      linearApiKey:
        typeof body.linearApiKey === "string"
          ? body.linearApiKey.trim()
          : undefined,
      linearAutoTransition:
        typeof body.linearAutoTransition === "boolean"
          ? body.linearAutoTransition
          : undefined,
      linearAutoTransitionStateId:
        typeof body.linearAutoTransitionStateId === "string"
          ? body.linearAutoTransitionStateId.trim()
          : undefined,
      linearAutoTransitionStateName:
        typeof body.linearAutoTransitionStateName === "string"
          ? body.linearAutoTransitionStateName.trim()
          : undefined,
      editorTabEnabled:
        typeof body.editorTabEnabled === "boolean"
          ? body.editorTabEnabled
          : undefined,
      attribution:
        typeof body.attribution === "boolean"
          ? body.attribution
          : undefined,
      sessionDefaults: body.sessionDefaults as import("../settings-manager.js").SessionDefaults | undefined,
    });

    return c.json({
      openrouterApiKeyConfigured: !!settings.openrouterApiKey.trim(),
      openrouterModel: settings.openrouterModel || DEFAULT_OPENROUTER_MODEL,
      linearApiKeyConfigured: !!settings.linearApiKey.trim(),
      linearAutoTransition: settings.linearAutoTransition,
      linearAutoTransitionStateName: settings.linearAutoTransitionStateName,
      editorTabEnabled: settings.editorTabEnabled,
      attribution: settings.attribution,
      sessionDefaults: settings.sessionDefaults,
    });
  });
}
