<?php
header('Content-Type: application/json');

if (!defined('AUTH_USER')) {
    http_response_code(401);
    echo json_encode(['ok'=>false,'error'=>'auth_required']);
    exit;
}
require_once(__DIR__ . '/../libs/mysqlmgmt.php');
require_once(__DIR__ . '/../libs/Sitesmith.php');
// validate_csrf_token() is defined in auto-prepend.php (loaded globally via .user.ini)

$pdo = (new mysqlmgmt())->getMySQLConnection();
$s   = new Sitesmith($pdo);
$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'entitlement':
            echo json_encode(['ok'=>true,'summary'=>$s->entitlementSummary(AUTH_USER)]);
            break;
        case 'history':
            $siteId = (int)($_GET['site_id'] ?? 0);
            if ($siteId <= 0) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'site_id_required']); break; }
            if (!sitesmith_user_owns_site($pdo, AUTH_USER, $siteId)) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'forbidden']); break; }
            echo json_encode(['ok'=>true,'messages'=>$s->getHistory(AUTH_USER, $siteId)]);
            break;
        case 'clear_history':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['ok'=>false,'error'=>'method']); break; }
            if (!validate_csrf_token()) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'csrf']); break; }
            $body = json_decode(file_get_contents('php://input'), true) ?: [];
            $siteId = (int)($body['site_id'] ?? 0);
            if ($siteId <= 0) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'site_id_required']); break; }
            if (!sitesmith_user_owns_site($pdo, AUTH_USER, $siteId)) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'forbidden']); break; }
            echo json_encode($s->clearHistory(AUTH_USER, $siteId));
            break;
        case 'send':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['ok'=>false,'error'=>'method']); break; }
            if (!validate_csrf_token()) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'csrf']); break; }
            $body = json_decode(file_get_contents('php://input'), true) ?: [];
            $siteId  = (int)($body['site_id'] ?? 0);
            $message = trim((string)($body['message'] ?? ''));
            $summary = (string)($body['canvas_summary'] ?? '');
            if ($siteId <= 0 || $message === '') { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'site_id_and_message_required']); break; }
            if (mb_strlen($message) > 4000) { http_response_code(413); echo json_encode(['ok'=>false,'error'=>'message_too_long']); break; }
            if (!sitesmith_user_owns_site($pdo, AUTH_USER, $siteId)) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'forbidden']); break; }
            $target = null;
            if (isset($body['target']) && is_array($body['target'])) {
                $rawTree = (string)($body['target']['tree_json'] ?? '');
                // Cap to keep prompt+tree under sane bounds (the AI bills per token
                // and an oversized tree can blow past the context window).
                if (mb_strlen($rawTree) > 30000) {
                    http_response_code(413); echo json_encode(['ok'=>false,'error'=>'target_tree_too_large']); break;
                }
                $target = [
                    'node_id'      => (string)($body['target']['node_id'] ?? ''),
                    'display_name' => (string)($body['target']['display_name'] ?? ''),
                    'tree_json'    => $rawTree,
                ];
                if ($target['node_id'] === '' || $target['tree_json'] === '') $target = null;
            }
            echo json_encode($s->send(AUTH_USER, $siteId, $message, $summary, $target));
            break;
        default:
            http_response_code(400);
            echo json_encode(['ok'=>false,'error'=>'unknown_action']);
    }
} catch (Throwable $e) {
    error_log('sitesmith api: '.$e->getMessage());
    http_response_code(500);
    echo json_encode(['ok'=>false,'error'=>'server_error']);
}

function sitesmith_user_owns_site(PDO $pdo, string $user, int $siteId): bool {
    if ($user === 'root') return true;
    $st = $pdo->prepare('SELECT 1 FROM whp.sites WHERE id=? AND username=?');
    $st->execute([$siteId, $user]);
    return (bool)$st->fetchColumn();
}
