<?php
/**
 * سودانا AI Engine — /api/engine/agents.php
 * CRUD for user agents
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/AIEngine.php';

$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$userId = (int)$u['id'];
$method = $_SERVER['REQUEST_METHOD'];
$b      = json_decode(file_get_contents('php://input'), true) ?? [];

if ($method === 'GET') {
    $agents = db()->prepare(
        "SELECT id, name, description, service, status, runs_total, last_run_at, created_at
         FROM ai_agents WHERE user_id=? AND status != 'deleted' ORDER BY created_at DESC"
    );
    $agents->execute([$userId]);
    json_response(['success'=>true,'agents'=>$agents->fetchAll()]);
}

if ($method === 'POST') {
    $action = $b['action'] ?? 'create';

    if ($action === 'create') {
        $name   = mb_substr(trim($b['name']   ?? ''), 0, 150);
        $prompt = mb_substr(trim($b['prompt'] ?? ''), 0, 2000);
        $svc    = preg_replace('/[^a-z]/', '', strtolower($b['service'] ?? 'general'));
        $desc   = mb_substr(trim($b['description'] ?? ''), 0, 500);
        if (!$name || !$prompt) Kernel::fail('name and prompt required', '', 400);

        // Enforce plan limits
        $cnt = db()->prepare("SELECT COUNT(*) FROM ai_agents WHERE user_id=? AND status='active'");
        $cnt->execute([$userId]);
        $plan  = $u['plan_key'] ?? 'free';
        $limit = match($plan) { 'pro'=>50, 'plus'=>10, default=>2 };
        if ((int)$cnt->fetchColumn() >= $limit) json_response(['error'=>'agent_limit_reached','upgrade'=>true], 403);

        db()->prepare(
            "INSERT INTO ai_agents (user_id, name, description, prompt, service, status, created_at) VALUES (?,?,?,?,?,'active',NOW())"
        )->execute([$userId, $name, $desc, $prompt, $svc]);
        json_response(['success'=>true,'agent_id'=>(int)db()->lastInsertId()]);
    }

    if ($action === 'delete') {
        $id = (int)($b['agent_id'] ?? 0);
        db()->prepare("UPDATE ai_agents SET status='deleted' WHERE id=? AND user_id=?")->execute([$id, $userId]);
        json_response(['success'=>true]);
    }

    if ($action === 'toggle') {
        $id = (int)($b['agent_id'] ?? 0);
        db()->prepare("UPDATE ai_agents SET status=IF(status='active','paused','active') WHERE id=? AND user_id=?")->execute([$id, $userId]);
        json_response(['success'=>true]);
    }
}

Kernel::fail('method_not_allowed', '', 405);
