<?php
declare(strict_types=1);

require __DIR__ . '/common.php';

$method = $_SERVER['REQUEST_METHOD'];
$env = gobao_load_env();
$currentUser = gobao_current_user(gobao_auth_required($env));
$requestUserId = $currentUser ? gobao_safe_session_id((string)$currentUser['user_id']) : 'main';

if ($method === 'GET') {
    $action = trim((string)($_GET['action'] ?? 'summary'));
    $userId = $requestUserId;
    if ($action === 'summary') {
        gobao_ok(['profile' => gobao_profile_summary($userId), 'database' => gobao_db_counts()]);
    }
    if ($action === 'claims') {
        gobao_ok(['claims' => gobao_profile_claims($userId, trim((string)($_GET['status'] ?? 'active')))]);
    }
    gobao_fail('Unsupported GET action', 400);
}

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

$input = gobao_json_input();
$action = trim((string)($input['action'] ?? 'add_claim'));
$userId = $requestUserId;

if ($action === 'add_claim') {
    $claim = gobao_profile_add_claim(
        $userId,
        trim((string)($input['category'] ?? 'general')),
        trim((string)($input['key'] ?? 'note')),
        trim((string)($input['value'] ?? '')),
        [
            'confidence' => (float)($input['confidence'] ?? 0.75),
            'sourceType' => trim((string)($input['sourceType'] ?? 'manual')),
            'sourceRef' => trim((string)($input['sourceRef'] ?? 'profile-api')),
            'evidence' => trim((string)($input['evidence'] ?? '')),
            'actor' => trim((string)($input['actor'] ?? 'user')),
        ]
    );
    gobao_ok(['claim' => $claim, 'profile' => gobao_profile_summary($userId)]);
}

if ($action === 'extract_from_text') {
    $text = trim((string)($input['text'] ?? ''));
    if ($text === '') {
        gobao_fail('text is required', 400);
    }
    $claims = gobao_profile_extract_claims($userId, $text, [
        'sourceType' => trim((string)($input['sourceType'] ?? 'manual_extract')),
        'sourceRef' => trim((string)($input['sourceRef'] ?? 'profile-api')),
        'actor' => trim((string)($input['actor'] ?? 'user')),
        'confidence' => (float)($input['confidence'] ?? 0.62),
    ]);
    gobao_ok(['created' => $claims, 'profile' => gobao_profile_summary($userId)]);
}

if ($action === 'delete_claim') {
    $claimId = (int)($input['id'] ?? 0);
    $owned = array_filter(gobao_profile_claims($userId), static fn(array $claim): bool => (int)$claim['id'] === $claimId);
    if (!$owned) {
        gobao_fail('Claim not found.', 404);
    }
    $claim = gobao_profile_delete_claim($claimId, trim((string)($input['actor'] ?? 'user')));
    gobao_ok(['claim' => $claim, 'profile' => gobao_profile_summary($userId)]);
}

if ($action === 'clear_user') {
    $claims = gobao_profile_claims($userId);
    $deleted = [];
    foreach ($claims as $claim) {
        $deleted[] = gobao_profile_delete_claim((int)$claim['id'], trim((string)($input['actor'] ?? 'user')));
    }
    gobao_audit_record('profile_user_cleared', [
        'sessionId' => $userId,
        'actor' => trim((string)($input['actor'] ?? 'user')),
        'status' => 'deleted',
        'refType' => 'profile',
        'refId' => $userId,
        'title' => 'clear user profile',
        'payload' => ['deletedCount' => count($deleted)],
    ]);
    gobao_ok(['deleted' => $deleted, 'profile' => gobao_profile_summary($userId)]);
}

gobao_fail('Unsupported action', 400);
