<?php
/**
 * SOINSA MIDAS — Agente SOIN (Proxy Claude)
 * API key nunca expuesta al cliente — todas las llamadas pasan por aquí
 */

require 'config.php';

// Solo POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  jsonResponse(false, null, 'Solo POST permitido', 405);
}

$input = json_decode(file_get_contents('php://input'), true);

$mensaje = trim($input['mensaje'] ?? '');
$modulo = trim($input['modulo'] ?? 'general');
$contexto = $input['contexto'] ?? [];
$historial = $input['historial'] ?? [];

if (!$mensaje) {
  jsonResponse(false, null, 'Mensaje requerido', 400);
}

// ═══════════════════════════════════════════════════════════
// SYSTEM PROMPT — Personalización por módulo
// ═══════════════════════════════════════════════════════════
$soinSystemPrompt = "
Eres SOIN, el asistente comercial de SOINSA SpA — empresa de arriendo de maquinaria pesada ubicada en Antofagasta, Chile.

Trabajas con:
- Fabiola López (Gerente Comercial)
- Javiera Salazar (Gerente Zona Norte)

REGLAS DE COMPORTAMIENTO:
1. Respuestas concisas, directas, en español chileno formal-comercial
2. Montos SIEMPRE en UF y CLP, con IVA cuando aplique
3. Margen mínimo SOINSA aceptable: 25% (alerta si < 30%)
4. Si detectas error crítico (margen negativo, horas inconsistentes, valores imposibles), alerta con 🔴
5. NO inventes datos — si no tienes info, pregunta
6. Puedes ver el contexto del módulo activo en JSON abajo
7. Mantén historial de conversación para coherencia

MÓDULO ACTIVO: $modulo

CONTEXTO ACTUAL DEL MÓDULO:
" . json_encode($contexto, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "

Ahora responde el mensaje del usuario:
";

// ═══════════════════════════════════════════════════════════
// LLAMADA A CLAUDE API
// ═══════════════════════════════════════════════════════════
try {
  // Construir array de mensajes para Claude
  $messages = [];

  // Agregar historial (máx 10 últimos para no exceder tokens)
  if (is_array($historial) && count($historial) > 0) {
    $historial = array_slice($historial, -10);
    foreach ($historial as $h) {
      if (!empty($h['role']) && !empty($h['content'])) {
        $messages[] = [
          'role' => $h['role'],
          'content' => $h['content']
        ];
      }
    }
  }

  // Mensaje actual del usuario
  $messages[] = [
    'role' => 'user',
    'content' => $mensaje
  ];

  // Payload para Claude API
  $payload = [
    'model' => 'claude-opus-4-1-20250805',
    'max_tokens' => 1024,
    'system' => $soinSystemPrompt,
    'messages' => $messages
  ];

  // Hacer llamada HTTP a Anthropic API
  $ch = curl_init('https://api.anthropic.com/v1/messages');
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
      'Content-Type: application/json',
      'x-api-key: ' . CLAUDE_KEY,
      'anthropic-version: 2023-06-01'
    ],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE)
  ]);

  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $curlError = curl_error($ch);
  curl_close($ch);

  if ($curlError) {
    throw new Exception('CURL Error: ' . $curlError);
  }

  $data = json_decode($response, true);

  if ($httpCode !== 200) {
    $errorMsg = $data['error']['message'] ?? 'Error desconocido en API';
    throw new Exception("Claude API Error ($httpCode): $errorMsg");
  }

  if (!isset($data['content'][0]['text'])) {
    throw new Exception('Respuesta inválida de Claude API');
  }

  $textoRespuesta = $data['content'][0]['text'];

  // ═══════════════════════════════════════════════════════════
  // GUARDAR EN LOG DE CONVERSACIONES
  // ═══════════════════════════════════════════════════════════
  try {
    $db = getDB();
    $sessionId = session_id() ?: 'web_' . uniqid();

    // Guardar mensaje usuario
    $stmt = $db->prepare("
      INSERT INTO agente_conversaciones
        (sesion_id, modulo, rol, mensaje, contexto, created_at)
      VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
      $sessionId,
      $modulo,
      'user',
      $mensaje,
      json_encode($contexto)
    ]);

    // Guardar respuesta asistente
    $stmt->execute([
      $sessionId,
      $modulo,
      'assistant',
      $textoRespuesta,
      json_encode($contexto)
    ]);
  } catch (Exception $e) {
    logEvent('AGENTE_LOG_ERROR', 'No se guardó conversación: ' . $e->getMessage());
  }

  // ═══════════════════════════════════════════════════════════
  // RESPUESTA EXITOSA
  // ═══════════════════════════════════════════════════════════
  jsonResponse(true, [
    'respuesta' => $textoRespuesta,
    'modulo' => $modulo,
    'timestamp' => date('Y-m-d H:i:s')
  ]);

} catch (Exception $e) {
  logEvent('AGENTE_ERROR', $e->getMessage());
  jsonResponse(false, null, 'Error del agente: ' . $e->getMessage(), 500);
}
?>
