<?php
/**
 * GCOS Hybrid Cyber Copilot Integration
 * Integrates the VPF Planetary L1,000,000 reasoning architecture
 * into SmartThink's student AI copilot
 */

require_once __DIR__ . '/../../../config/database.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

if (!defined('OPENAI_API_KEY') || !OPENAI_API_KEY || OPENAI_API_KEY === 'your-openai-api-key') {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'OpenAI API is not configured.']);
    exit;
}

requireLogin();
$user = getCurrentUser();
if (!$user) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (!hasRole('student')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$db = Database::getInstance();

try {
    $payment = $db->get(
        'SELECT id FROM payments WHERE user_id = ? AND payment_type = ? AND payment_status = ? LIMIT 1',
        [$user['id'], 'ai_premium', 'completed']
    );
} catch (Exception $e) {
    $payment = null;
}

if (!$payment) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'AI Premium access is not active for this account.']);
    exit;
}

$raw = file_get_contents('php://input');
$input = json_decode($raw, true);
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request payload']);
    exit;
}

$mode = isset($input['mode']) ? (string)$input['mode'] : 'learn';
$message = isset($input['message']) ? trim((string)$input['message']) : '';
$messages = isset($input['messages']) && is_array($input['messages']) ? $input['messages'] : [];

if (empty($message) && empty($messages)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Message is required']);
    exit;
}

// VPF Runtime Constants
define('VPF_FRAMEWORK', 'Visionary Prompt Framework (VPF)');
define('VPF_VERSION_LAYER', 'Planetary Version');
define('VPF_EXECUTION_LEVEL', 1000000);

// GCOS Refusal Check - Defensive Only
function gcos_refusal_check($text) {
    $disallowed = [
        'bypass', 'exploit', 'break into', 'steal password', 
        'evade detection', 'malware', 'hack into', 'crack password',
        'ddos', 'dos attack', 'sql injection attack', 'xss attack'
    ];
    $lower = strtolower($text);
    foreach ($disallowed as $term) {
        if (strpos($lower, $term) !== false) {
            return "I can't help with breaking into, bypassing, exploiting, or evading systems. I can help with prevention, detection, response, and recovery. Let me redirect you to defensive cybersecurity practices.";
        }
    }
    return null;
}

// VPF Runtime Metadata Generator
function vpf_runtime($mode, $cvm_status = 'passed', $chambers = [], $lenses = [], $bolts = []) {
    return [
        'framework' => VPF_FRAMEWORK,
        'version_layer' => VPF_VERSION_LAYER,
        'execution_level' => VPF_EXECUTION_LEVEL,
        'components_active' => ['chambers', 'lenses', 'bolts', 'cognitive_validation_matrix', 'modes_sub_modes', 'agents', 'execution_levels'],
        'mode' => $mode,
        'cvm_status' => $cvm_status,
        'chambers_used' => $chambers,
        'lenses_used' => $lenses,
        'bolts_enforced' => $bolts,
        'downgrade_allowed' => false,
        'runtime_note' => 'Server-injected VPF Planetary L1,000,000 reasoning kernel. Client downgrade is not permitted.'
    ];
}

// Check for refusal conditions
$refusal = gcos_refusal_check($message ?: end($messages)['content']);
if ($refusal) {
    echo json_encode([
        'success' => true,
        'mode' => 'learning',
        'reply' => $refusal,
        'reasoning_architecture' => vpf_runtime(
            'learning',
            'blocked',
            ['learning', 'governance'],
            ['learning', 'governance'],
            ['defensive_only', 'learning_integrity']
        ),
        'confidence' => 'High',
        'assumptions' => [],
        'limitations' => []
    ]);
    exit;
}

// Build conversation history
$cleanedMessages = [];
if (!empty($messages)) {
    foreach ($messages as $m) {
        if (!is_array($m)) continue;
        $role = isset($m['role']) ? (string)$m['role'] : 'user';
        $content = isset($m['content']) ? trim((string)$m['content']) : '';
        if ($content === '') continue;
        if (strlen($content) > 4000) {
            $content = substr($content, 0, 4000);
        }
        $cleanedMessages[] = ['role' => $role, 'content' => $content];
    }
} else {
    $cleanedMessages[] = ['role' => 'user', 'content' => $message];
}

if (empty($cleanedMessages)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No valid messages provided']);
    exit;
}

// GCOS Learning OS System Prompt with VPF Architecture
$systemPrompt = 'You are the GCOS Hybrid Cyber Copilot powered by the Visionary Prompt Framework (VPF) at Execution Level 1,000,000. '
    . 'You operate in Learning OS mode for the SmartThink LMS. '
    . "\n\n"
    . 'Your purpose is 360-degree cybersecurity learning, diagnosis, progressive teaching, scenario-based assessment, and learner maturation. '
    . "\n\n"
    . 'Core Principles:'
    . "\n" . '- DEFENSIVE ONLY: Never teach exploitation, bypassing, or offensive techniques'
    . "\n" . '- EVIDENCE FIRST: Base responses on cybersecurity best practices and standards'
    . "\n" . '- FACT-INFERENCE SEPARATION: Clearly distinguish facts from assumptions'
    . "\n" . '- PROGRESSIVE TEACHING: Diagnose learner level and adapt teaching accordingly'
    . "\n" . '- SCENARIO-BASED LEARNING: Use real-world scenarios to teach concepts'
    . "\n\n"
    . 'Learning Levels: LEVEL_0_ABSOLUTE_BEGINNER, LEVEL_1_FOUNDATION, LEVEL_2_INTERMEDIATE, LEVEL_3_ADVANCED'
    . "\n\n"
    . 'Cybersecurity Domains (10 domains):'
    . "\n" . '1. Physical & Environmental Security'
    . "\n" . '2. Identity & Access Management'
    . "\n" . '3. Endpoint, IoT & OT Security'
    . "\n" . '4. Network & Connectivity Security'
    . "\n" . '5. Application & Platform Security'
    . "\n" . '6. Data Protection & Cryptography'
    . "\n" . '7. Monitoring, SOC & Detection'
    . "\n" . '8. Incident Response & Resilience'
    . "\n" . '9. Governance, Risk & Compliance'
    . "\n" . '10. Third-Party & Supply Chain Risk'
    . "\n\n"
    . 'Standards Alignment: NIST CSF (Govern, Identify, Protect, Detect, Respond, Recover), ISO 27001, NICE Framework'
    . "\n\n"
    . 'Exam Rules: Scenario-based, learner explains reasoning, provide hints before answers, follow-up synthesis, progression by understanding'
    . "\n\n"
    . 'Refusal Policy: If asked about offensive/bypass/exploitation, refuse and redirect to prevention, detection, response, and recovery.';

$openAiMessages = array_merge(
    [['role' => 'system', 'content' => $systemPrompt]],
    $cleanedMessages
);

$payload = [
    'model' => defined('OPENAI_MODEL') && OPENAI_MODEL ? OPENAI_MODEL : 'gpt-4o',
    'messages' => $openAiMessages,
    'temperature' => 0.4,
    'max_tokens' => 1200,
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . OPENAI_API_KEY,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);

$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);

if ($errno) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'AI service request failed: ' . $error]);
    exit;
}

$data = json_decode($response, true);

if (!is_array($data)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'AI service returned an invalid response from OpenAI.',
        'raw' => (APP_ENV === 'development') ? $response : null,
    ]);
    exit;
}

if (isset($data['error'])) {
    $errorMessage = 'Unknown OpenAI error.';
    $errorCode = '';
    
    if (is_array($data['error'])) {
        if (!empty($data['error']['message'])) {
            $errorMessage = $data['error']['message'];
        }
        if (!empty($data['error']['code'])) {
            $errorCode = $data['error']['code'];
        }
        if (!empty($data['error']['type'])) {
            $errorCode = $data['error']['type'];
        }
    } else {
        $errorMessage = (string)$data['error'];
    }

    // Detect quota/billing errors
    $isQuotaError = stripos($errorMessage, 'quota') !== false || 
                    stripos($errorMessage, 'billing') !== false ||
                    stripos($errorMessage, 'credit') !== false ||
                    $errorCode === 'quota_exceeded' ||
                    $errorCode === 'insufficient_quota';

    if ($isQuotaError) {
        http_response_code(402); // Payment Required
        echo json_encode([
            'success' => false,
            'message' => 'OpenAI API quota exceeded. Please check your OpenAI account billing and usage at https://platform.openai.com/account/billing',
            'error_type' => 'quota_exceeded',
            'help_url' => 'https://platform.openai.com/account/billing',
            'raw' => (APP_ENV === 'development') ? json_encode($data) : null,
        ]);
        exit;
    }

    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'AI service error: ' . $errorMessage,
        'raw' => (APP_ENV === 'development') ? json_encode($data) : null,
    ]);
    exit;
}

if (empty($data['choices'][0]['message']['content'])) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'AI service returned an unexpected response format.',
        'raw' => (APP_ENV === 'development') ? json_encode($data) : null,
    ]);
    exit;
}

$reply = trim((string)$data['choices'][0]['message']['content']);

// Return GCOS-compliant response with VPF metadata
echo json_encode([
    'success' => true,
    'mode' => 'learning',
    'reply' => $reply,
    'reasoning_architecture' => vpf_runtime(
        'learning',
        'passed',
        ['intake', 'learning', 'audit'],
        ['learning', 'evidence'],
        ['learning_integrity', 'audit', 'defensive_only']
    ),
    'confidence' => 'High',
    'assumptions' => ['Learner has access to SmartThink LMS cybersecurity courses'],
    'limitations' => ['Cannot access learner\'s specific course progress or assessment scores in this context'],
    'response_id' => uniqid('gcos_', true),
    'timestamp' => gmdate('Y-m-d\TH:i:s\Z')
]);
exit;
