<?php
declare(strict_types=1);

require __DIR__ . '/common.php';
require_once __DIR__ . '/mind.php';

$env = gobao_load_env();
gobao_ok([
    'name' => 'gobao-server-brain-api',
    'version' => GOBAO_API_VERSION,
    'auth' => [
        'enabled' => gobao_auth_required($env),
        'endpoint' => '/auth.php',
        'devicePairing' => true,
        'pairingTtlSeconds' => 3600,
        'deviceTokens' => 'per-device-hashed',
        'legacyCompanionTokenAllowed' => !in_array(
            strtolower(trim((string)($env['GOBAO_ALLOW_LEGACY_COMPANION_TOKEN'] ?? 'true'))),
            ['0', 'false', 'no', 'off'],
            true
        ),
    ],
    'tools' => [
        'enabled' => true,
        'endpoint' => '/tools.php',
        'queueTable' => 'tool_runs',
    ],
    'phase2' => [
        'enabled' => true,
        'name' => 'human-like-workflow',
        'tools' => [
            'scheduled_learning_tick',
            'knowledge_freshness_tick',
            'profile_digest',
            'metrics_summary',
            'tool_reliability_score',
            'phase2_daily_review',
        ],
        'autoLearnIntervalMinutes' => (int)($env['GOBAO_AUTO_LEARN_INTERVAL_MINUTES'] ?? 360),
        'reviewLimit' => (int)($env['GOBAO_PHASE2_REVIEW_LIMIT'] ?? 35),
    ],
    'phase3' => [
        'enabled' => true,
        'name' => 'local-device-control',
        'tools' => ['windows_companion_action', 'android_adb_action', 'pyautogui_action', 'browser_task', 'web_crawl', 'shopping_prepare', 'code_execute', 'local_capability_status'],
        'sandboxExecution' => [
            'mode' => 'local-container-only',
            'hostFallback' => false,
            'networkDefault' => 'none',
            'requiresApproval' => false,
        ],
        'highRiskToolsEnabled' => in_array(strtolower(trim((string)($env['GOBAO_HIGH_RISK_TOOLS_ENABLED'] ?? 'false'))), ['1', 'true', 'yes', 'on', 'enabled'], true),
        'companionTokenConfigured' => trim((string)($env['GOBAO_COMPANION_TOKEN'] ?? $env['GOBAO_COMPANION_SHARED_SECRET'] ?? '')) !== '',
        'configuredDefaultDryRun' => in_array(strtolower(trim((string)($env['GOBAO_STAGE3_DEFAULT_DRY_RUN'] ?? 'false'))), ['1', 'true', 'yes', 'on', 'enabled'], true),
        'configuredRequireLocalConfirm' => in_array(strtolower(trim((string)($env['GOBAO_STAGE3_REQUIRE_LOCAL_CONFIRM'] ?? 'false'))), ['1', 'true', 'yes', 'on', 'enabled'], true),
        'defaultDryRun' => false,
        'requireLocalConfirm' => false,
        'policyScope' => 'low_risk_automatic_high_risk_confirmed',
        'autoApproveLowRisk' => true,
        'humanConfirmationBoundary' => [
            'payment_or_transfer',
            'otp_or_face_verification',
            'credential_or_secret_change',
            'public_post_or_message_as_user',
            'destructive_or_irreversible_action',
        ],
        'visualControl' => [
            'windowsAppInventory' => true,
            'windowsUiAutomation' => true,
            'desktopVision' => 'qwen-vl-on-demand',
            'androidAppInventory' => true,
            'androidScreenVision' => 'qwen-vl-on-demand',
            'continuousScreenRecording' => false,
        ],
    ],
    'mind' => gobao_mind_status($env),
    'profile' => [
        'enabled' => true,
        'endpoint' => '/profile.php',
        'table' => 'profile_claims',
    ],
    'audit' => [
        'enabled' => true,
        'endpoint' => '/audit.php',
        'table' => 'audit_events',
    ],
    'userKnowledgeBase' => [
        'enabled' => true,
        'endpoint' => '/user_kb.php',
        'defaultConsent' => !empty(gobao_user_kb_settings('main')['enabled']),
        'writeAllowed' => !empty(gobao_user_kb_settings('main')['writeAllowed']),
        'useForAnswer' => !empty(gobao_user_kb_settings('main')['useForAnswer']),
        'serverSync' => !empty(gobao_user_kb_settings('main')['syncServer']),
        'serverSyncDir' => gobao_user_kb_server_dir('main', $env),
        'table' => 'user_kb_settings',
    ],
    'localCompanion' => [
        'enabled' => true,
        'endpoint' => '/companion.php',
        'tables' => ['local_devices', 'local_vault_syncs', 'device_pairings'],
    ],
    'taskBrain' => [
        'enabled' => true,
        'endpoint' => '/task_brain.php',
        'tables' => ['agent_tasks', 'agent_task_steps'],
    ],
    'workbuddy' => [
        'enabled' => trim((string)($env['WORKBUDDY_API_BASE'] ?? '')) !== ''
            && trim((string)($env['WORKBUDDY_API_KEY'] ?? '')) !== '',
        'baseConfigured' => trim((string)($env['WORKBUDDY_API_BASE'] ?? '')) !== '',
        'apiKeyConfigured' => trim((string)($env['WORKBUDDY_API_KEY'] ?? '')) !== '',
        'endpoint' => '/tools.php',
        'tools' => [
            'workbuddy_status',
            'workbuddy_search',
            'workbuddy_get',
            'workbuddy_create_task',
            'workbuddy_run_workflow',
        ],
        'paths' => [
            'search' => trim((string)($env['WORKBUDDY_SEARCH_PATH'] ?? '/search')),
            'get' => trim((string)($env['WORKBUDDY_GET_PATH'] ?? '/items/{id}')),
            'createTask' => trim((string)($env['WORKBUDDY_CREATE_TASK_PATH'] ?? '/tasks')),
            'runWorkflow' => trim((string)($env['WORKBUDDY_WORKFLOW_PATH'] ?? '/workflows/{id}/run')),
        ],
    ],
    'configured' => gobao_configured_brains($env),
    'modelFallback' => [
        'enabled' => gobao_model_fallback_enabled($env),
        'orderIfQwenPrimary' => array_map(static fn($cfg) => [
            'provider' => $cfg['provider'] ?? '',
            'model' => $cfg['model'] ?? '',
            'configured' => !empty($cfg['key']),
        ], gobao_model_fallback_order(gobao_brain_config('qwen', $env), $env)),
        'orderIfDeepSeekPrimary' => array_map(static fn($cfg) => [
            'provider' => $cfg['provider'] ?? '',
            'model' => $cfg['model'] ?? '',
            'configured' => !empty($cfg['key']),
        ], gobao_model_fallback_order(gobao_brain_config('deepseek', $env), $env)),
    ],
    'search' => gobao_search_configured($env),
    'githubAutoIngest' => [
        'enabled' => gobao_github_auto_enabled($env),
        'defaultLimit' => gobao_github_auto_limit('', $env),
        'maxFileBytes' => (int)($env['GITHUB_AUTO_MAX_FILE_BYTES'] ?? 80000),
        'obsidianSync' => gobao_github_auto_obsidian_enabled($env),
        'githubTokenConfigured' => !empty($env['GITHUB_TOKEN']),
        'fileArchiveEnabled' => gobao_github_file_archive_enabled($env),
        'fileArchiveRoot' => gobao_github_file_archive_root($env),
    ],
    'database' => gobao_db_counts(),
    'obsidian' => gobao_obsidian_status($env),
    'knowledgeFreshness' => gobao_knowledge_freshness_summary($env),
    'selfHeal' => gobao_self_heal_status(),
    'memoryDir' => gobao_memory_dir(),
]);
