import { z } from 'zod';

const KOREAN_REGEX = /[가-힣]/;
const KEBAB_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;

const RawResponseSchema = z.object({
  title: z.string().trim().min(1).max(200),
  summary: z.string().min(1),
  tags: z.array(z.string()).default([]),
  due_date: z.string().regex(ISO_DATE_REGEX).nullable().optional()
});

export interface AiResponse {
  title: string;
  summary: string;
  tags: string[];
  dueDate: string | null;
}

function normalizeSummary(raw: string): string {
  const lines = raw.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
  if (lines.length === 0) throw new Error('summary is empty');
  if (lines.length === 3) return lines.join('\n');
  if (lines.length < 3) {
    while (lines.length < 3) lines.push('');
    return lines.join('\n');
  }
  const head = lines.slice(0, 2);
  const tail = lines.slice(2).join(' ');
  return [...head, tail].join('\n');
}

function validateDueDate(d: string | null | undefined): string | null {
  if (d === null || d === undefined) return null;
  // Re-verify the date is actually valid (regex passes 2026-13-99 which is invalid)
  const dt = new Date(d + 'T00:00:00Z');
  if (Number.isNaN(dt.getTime()) || dt.toISOString().slice(0, 10) !== d) return null;
  return d;
}

export function parseAiResponse(raw: unknown): AiResponse {
  const parsed = RawResponseSchema.parse(raw);
  if (!KOREAN_REGEX.test(parsed.title)) {
    throw new Error('title must contain Korean characters');
  }
  return {
    title: parsed.title.slice(0, 60),
    summary: normalizeSummary(parsed.summary),
    tags: parsed.tags.filter((t) => KEBAB_REGEX.test(t)).slice(0, 3),
    dueDate: validateDueDate(parsed.due_date)
  };
}
