import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

// ─── Catégorisation automatique des dépenses ─────────────────
export async function categorizeExpense(
  description: string,
  amount: number,
  categories: string[]
): Promise<{ category: string; confidence: number; explanation: string }> {
  const response = await anthropic.messages.create({
    model: "claude-haiku-4-5-20251001",
    max_tokens: 256,
    system: `Tu es un expert comptable français. Catégorise les dépenses d'entreprise.
Réponds UNIQUEMENT en JSON: {"category": "nom_categorie", "confidence": 0.95, "explanation": "raison courte"}`,
    messages: [
      {
        role: "user",
        content: `Dépense: "${description}" — Montant: ${amount}€
Catégories disponibles: ${categories.join(", ")}
Quelle catégorie correspond le mieux ?`,
      },
    ],
  });

  try {
    const content = response.content[0];
    if (content.type !== "text") throw new Error("Unexpected response type");
    const json = JSON.parse(content.text);
    return {
      category: json.category,
      confidence: Math.min(1, Math.max(0, json.confidence ?? 0.5)),
      explanation: json.explanation ?? "",
    };
  } catch {
    return { category: categories[categories.length - 1] ?? "Autres", confidence: 0.3, explanation: "" };
  }
}

// ─── Assistant comptable IA ───────────────────────────────────
export async function askAccountingAssistant(
  question: string,
  context: {
    organizationName: string;
    recentTransactions?: Array<{ description: string; amount: number; type: string }>;
  }
): Promise<string> {
  const contextSummary = context.recentTransactions
    ? `Transactions récentes: ${context.recentTransactions
        .slice(0, 5)
        .map((t) => `${t.description}: ${t.amount}€ (${t.type})`)
        .join(", ")}`
    : "";

  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    system: `Tu es un assistant comptable expert pour les PME françaises (TVA, PCG, liasse fiscale).
Tu aides les utilisateurs de ${context.organizationName} à comprendre leur comptabilité.
Réponds en français, de façon concise et pratique. ${contextSummary}`,
    messages: [{ role: "user", content: question }],
  });

  const content = response.content[0];
  return content.type === "text" ? content.text : "Je ne peux pas répondre pour le moment.";
}

// ─── Prédiction de trésorerie ─────────────────────────────────
export async function forecastCashflow(data: {
  monthlyRevenues: number[];
  monthlyExpenses: number[];
  currentBalance: number;
}): Promise<{
  nextMonthRevenue: number;
  nextMonthExpense: number;
  nextMonthBalance: number;
  trend: "positive" | "negative" | "stable";
  advice: string;
}> {
  const avgRevenue = data.monthlyRevenues.reduce((a, b) => a + b, 0) / (data.monthlyRevenues.length || 1);
  const avgExpense = data.monthlyExpenses.reduce((a, b) => a + b, 0) / (data.monthlyExpenses.length || 1);

  const response = await anthropic.messages.create({
    model: "claude-haiku-4-5-20251001",
    max_tokens: 512,
    system: `Expert en prévisions financières PME. Réponds en JSON strict:
{"nextMonthRevenue":number,"nextMonthExpense":number,"nextMonthBalance":number,"trend":"positive"|"negative"|"stable","advice":"conseil court en français"}`,
    messages: [
      {
        role: "user",
        content: `Revenus mensuels (6 derniers mois): ${data.monthlyRevenues.join(", ")}€
Dépenses mensuelles: ${data.monthlyExpenses.join(", ")}€
Solde actuel: ${data.currentBalance}€
Moyenne revenus: ${avgRevenue.toFixed(0)}€ / Moyenne dépenses: ${avgExpense.toFixed(0)}€
Prévisions pour le mois prochain ?`,
      },
    ],
  });

  try {
    const content = response.content[0];
    if (content.type !== "text") throw new Error();
    return JSON.parse(content.text);
  } catch {
    const nextRevenue = avgRevenue * 1.02;
    const nextExpense = avgExpense * 1.01;
    return {
      nextMonthRevenue: Math.round(nextRevenue),
      nextMonthExpense: Math.round(nextExpense),
      nextMonthBalance: Math.round(data.currentBalance + nextRevenue - nextExpense),
      trend: nextRevenue > nextExpense ? "positive" : "negative",
      advice: "Maintenez un contrôle rigoureux de vos dépenses.",
    };
  }
}

// ─── Détection d'anomalies ────────────────────────────────────
export async function detectAnomalies(transactions: Array<{
  description: string;
  amount: number;
  date: string;
  category: string;
}>): Promise<Array<{ transactionIndex: number; reason: string; severity: "low" | "medium" | "high" }>> {
  if (transactions.length === 0) return [];

  const response = await anthropic.messages.create({
    model: "claude-haiku-4-5-20251001",
    max_tokens: 1024,
    system: `Expert en détection de fraudes et anomalies comptables.
Analyse les transactions et retourne les anomalies en JSON:
[{"transactionIndex":0,"reason":"explication","severity":"low|medium|high"}]
Retourne [] si aucune anomalie.`,
    messages: [
      {
        role: "user",
        content: `Transactions à analyser:\n${JSON.stringify(transactions.slice(0, 20), null, 2)}`,
      },
    ],
  });

  try {
    const content = response.content[0];
    if (content.type !== "text") return [];
    return JSON.parse(content.text) ?? [];
  } catch {
    return [];
  }
}

// ─── Analyse OCR justificatif ─────────────────────────────────
export async function extractReceiptData(base64Image: string, mediaType: string): Promise<{
  vendor: string;
  amount: number;
  taxAmount: number;
  date: string;
  description: string;
  category: string;
}> {
  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 512,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "image",
            source: {
              type: "base64",
              media_type: mediaType as "image/jpeg" | "image/png" | "image/gif" | "image/webp",
              data: base64Image,
            },
          },
          {
            type: "text",
            text: `Extrait les informations de ce justificatif/reçu en JSON:
{"vendor":"nom_fournisseur","amount":00.00,"taxAmount":00.00,"date":"YYYY-MM-DD","description":"description","category":"catégorie_probable"}`,
          },
        ],
      },
    ],
  });

  try {
    const content = response.content[0];
    if (content.type !== "text") throw new Error();
    return JSON.parse(content.text);
  } catch {
    return { vendor: "", amount: 0, taxAmount: 0, date: "", description: "", category: "Autres" };
  }
}
