import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily, requireOwnership } from "@/lib/auth";
import { getAgeInMonths, guidelines } from "@/lib/guidelines";

const LITELLM_URL = process.env.LITELLM_BASE_URL || "https://llm.manohargupta.com";
const LITELLM_KEY = process.env.LITELLM_API_KEY;

// Generate plausible daily logs for a child based on age
async function generateHistory(childId: string, birthDate: string): Promise<string> {
  const ageMonths = getAgeInMonths(birthDate);
  const guide = guidelines.find((g) => ageMonths >= g.minAgeMonths && ageMonths < g.maxAgeMonths)
    || guidelines[guidelines.length - 1];

  const daysBack = Math.min(ageMonths * 30, 365); // Cap at 1 year
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - daysBack);

  // Build prompt for AI to generate log entries
  const prompt = `Generate ${daysBack} days of baby logs. For each day, create 3-5 entries with timestamps.

Child age: ${ageMonths} months
Typical routine: ${guide.feeds.times} feeds/day, ${guide.sleep.totalHours}h sleep, ${guide.diapers.count} diaper changes/day

Return as JSON array with objects containing:
- type: "feed", "sleep", or "diaper"
- subType: "breast_left", "breast_right", "bottle", "nap", "night_sleep", "wet", "dirty", "both"
- loggedAt: ISO timestamp
- amountMl: number (for bottles)
- notes: optional string

Make times realistic - feeds every 3-4 hours during day, sleep at night, diapers after feeds and naps.
Just return the JSON, no explanation.`;

  try {
    const response = await fetch(`${LITELLM_URL}/v1/chat/completions`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${LITELLM_KEY}`,
      },
      body: JSON.stringify({
        model: "minimax-2.7",
        messages: [{ role: "user", content: prompt }],
        temperature: 0.7,
      }),
    });

    if (!response.ok) {
      throw new Error(`LiteLLM error: ${response.status}`);
    }

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content;
    return content || "[]";
  } catch (error) {
    console.error("AI generation failed:", error);
    return "[]";
  }
}

export async function POST(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { childId, birthDate } = body;

    if (!childId || !birthDate) {
      return NextResponse.json({ error: "childId and birthDate required" }, { status: 400 });
    }

    const ownership = await requireOwnership(childId, "children", "Child");
    if (!ownership.success) {
      return NextResponse.json({ error: ownership.error }, { status: ownership.status });
    }

    const content = await generateHistory(childId, birthDate);

    // Parse and insert logs
    let logs: any[] = [];
    try {
      logs = JSON.parse(content);
    } catch {
      logs = [];
    }

    let inserted = 0;
    for (const log of logs) {
      try {
        if (log.type === "feed") {
          await sql.unsafe(
            `INSERT INTO feeds (child_id, type, method, amount_ml, notes, logged_at) VALUES ($1, $2, $3, $4, $5, $6)`,
            [childId, log.subType || "bottle", log.subType?.includes("breast") ? "breast_both" : "bottle", log.amountMl || null, log.notes || null, log.loggedAt]
          );
          inserted++;
        } else if (log.type === "diaper") {
          await sql.unsafe(
            `INSERT INTO diapers_logs (child_id, type, notes, logged_at) VALUES ($1, $2, $3, $4)`,
            [childId, log.subType || "wet", log.notes || null, log.loggedAt]
          );
          inserted++;
        } else if (log.type === "sleep") {
          await sql.unsafe(
            `INSERT INTO sleeps (child_id, type, started_at, notes, logged_at) VALUES ($1, $2, $3, $4, $5)`,
            [childId, log.subType || "nap", log.loggedAt, log.notes || null, log.loggedAt]
          );
          inserted++;
        }
      } catch (e) {
        // Skip individual insert errors
      }
    }

    return NextResponse.json({ success: true, generated: inserted });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}