<?php
declare(strict_types=1);

require __DIR__ . '/common.php';

$env = gobao_load_env();
$method = $_SERVER['REQUEST_METHOD'];

function gobao_user_kb_input_user(array $input = []): string {
    global $env;
    return gobao_request_user_id($env, 'main');
}

if ($method === 'GET') {
    $action = trim((string)($_GET['action'] ?? 'status'));
    $userId = gobao_user_kb_input_user();
    if ($action === 'status') {
        $dir = gobao_user_kb_server_dir($userId, $env);
        gobao_ok([
            'settings' => gobao_user_kb_settings($userId),
            'profile' => gobao_profile_summary($userId),
            'server' => [
                'dir' => $dir,
                'profilePath' => $dir . '/profile.md',
                'profileExists' => is_file($dir . '/profile.md'),
            ],
        ]);
    }
    if ($action === 'export') {
        gobao_ok([
            'settings' => gobao_user_kb_settings($userId),
            'markdown' => gobao_user_kb_markdown($userId),
        ]);
    }
    gobao_fail('Unsupported GET action', 400);
}

if ($method !== 'POST') {
    gobao_fail('POST required', 405);
}

$input = gobao_json_input();
$action = trim((string)($input['action'] ?? 'status'));
$userId = gobao_user_kb_input_user($input);
$actor = trim((string)($input['actor'] ?? 'user'));

if ($action === 'grant') {
    $settings = gobao_user_kb_update_settings($userId, [
        'enabled' => true,
        'writeAllowed' => true,
        'useForAnswer' => true,
        'syncServer' => !empty($input['syncServer']),
        'localMode' => trim((string)($input['localMode'] ?? 'browser')),
        'settings' => [
            'consentedAt' => gmdate('c'),
            'consentText' => 'User allowed GOBAO to create and update a personal knowledge base.',
            'device' => trim((string)($input['device'] ?? 'unknown')),
        ],
    ], $actor);
    $server = !empty($settings['syncServer']) ? gobao_user_kb_write_server($userId, $env, is_array($input['docs'] ?? null) ? $input['docs'] : []) : ['written' => false, 'reason' => 'sync_disabled'];
    gobao_ok(['settings' => $settings, 'server' => $server, 'markdown' => gobao_user_kb_markdown($userId, is_array($input['docs'] ?? null) ? $input['docs'] : [])]);
}

if ($action === 'settings') {
    $patch = [];
    foreach (['enabled', 'writeAllowed', 'useForAnswer', 'syncServer'] as $key) {
        if (array_key_exists($key, $input)) {
            $patch[$key] = (bool)$input[$key];
        }
    }
    if (array_key_exists('localMode', $input)) {
        $patch['localMode'] = trim((string)$input['localMode']);
    }
    if (is_array($input['settings'] ?? null)) {
        $patch['settings'] = $input['settings'];
    }
    $settings = gobao_user_kb_update_settings($userId, $patch, $actor);
    $server = !empty($settings['syncServer']) ? gobao_user_kb_write_server($userId, $env, is_array($input['docs'] ?? null) ? $input['docs'] : []) : ['written' => false, 'reason' => 'sync_disabled'];
    gobao_ok(['settings' => $settings, 'server' => $server]);
}

if ($action === 'sync') {
    $settings = gobao_user_kb_settings($userId);
    if (empty($settings['enabled'])) {
        gobao_fail('Personal knowledge base is not enabled by user consent.', 403);
    }
    $docs = is_array($input['docs'] ?? null) ? $input['docs'] : [];
    $server = gobao_user_kb_write_server($userId, $env, $docs);
    gobao_ok([
        'settings' => $settings,
        'server' => $server,
        'markdown' => gobao_user_kb_markdown($userId, $docs),
    ]);
}

if ($action === 'pause') {
    $settings = gobao_user_kb_update_settings($userId, [
        'enabled' => true,
        'writeAllowed' => false,
        'useForAnswer' => !empty($input['useForAnswer']),
    ], $actor);
    gobao_ok(['settings' => $settings]);
}

if ($action === 'resume') {
    $settings = gobao_user_kb_update_settings($userId, [
        'enabled' => true,
        'writeAllowed' => true,
        'useForAnswer' => true,
    ], $actor);
    gobao_ok(['settings' => $settings]);
}

if ($action === 'clear') {
    $claims = gobao_profile_claims($userId);
    $deleted = [];
    foreach ($claims as $claim) {
        $deleted[] = gobao_profile_delete_claim((int)$claim['id'], $actor);
    }
    $serverDeleted = gobao_user_kb_delete_server($userId, $env);
    $settings = gobao_user_kb_update_settings($userId, [
        'enabled' => false,
        'writeAllowed' => false,
        'useForAnswer' => false,
        'syncServer' => false,
        'settings' => ['clearedAt' => gmdate('c')],
    ], $actor);
    gobao_audit_record('user_kb_cleared', [
        'sessionId' => $userId,
        'actor' => $actor,
        'status' => 'deleted',
        'refType' => 'user_kb',
        'refId' => $userId,
        'title' => 'clear personal knowledge base',
        'payload' => ['deletedClaims' => count($deleted), 'serverDeleted' => $serverDeleted],
    ]);
    gobao_ok(['settings' => $settings, 'deletedClaims' => $deleted, 'serverDeleted' => $serverDeleted]);
}

gobao_fail('Unsupported action', 400);
