<?php
/**
 * RBC Chat Router
 * Classifies admin natural-language messages and routes to the correct action handler.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../config.php';
}
require_once __DIR__ . '/provider_engine.php';
require_once __DIR__ . '/actions/send_fee_reminders.php';
require_once __DIR__ . '/actions/generate_terminal_reports.php';
require_once __DIR__ . '/actions/generate_exam_paper.php';
require_once __DIR__ . '/actions/detect_at_risk_students.php';
require_once __DIR__ . '/actions/financial_snapshot.php';
require_once __DIR__ . '/actions/send_weekly_feeding_summary.php';
require_once __DIR__ . '/actions/check_timetable_conflicts.php';
require_once __DIR__ . '/actions/bulk_notify_parents.php';
require_once __DIR__ . '/actions/batch_generate_report_pdfs.php';
require_once __DIR__ . '/actions/create_parent_accounts_bulk.php';
require_once __DIR__ . '/actions/send_whatsapp_broadcast.php';
require_once __DIR__ . '/actions/deliver_reports_whatsapp.php';

if (!function_exists('rbcGetCurrentTerm')) {
    /**
     * Current academic term — delegates to the canonical getCurrentTerm().
     * The month table this replaces mapped Jan-Apr to "First Term", which
     * contradicted both config.php and school_context.php.
     */
    function rbcGetCurrentTerm(): string {
        if (function_exists('getCurrentTerm')) {
            return (string) getCurrentTerm();
        }
        return (string) (getSettingValue('current_term') ?: 'First Term');
    }
}

class RBCChatRouter {

    private static $action_map = [
        'send_fee_reminders'          => 'action_send_fee_reminders',
        'generate_terminal_reports'   => 'action_generate_terminal_reports',
        'generate_exam_paper'         => 'action_generate_exam_paper',
        'detect_at_risk_students'     => 'action_detect_at_risk_students',
        'financial_snapshot'          => 'action_financial_snapshot',
        'send_weekly_feeding_summary' => 'action_send_weekly_feeding_summary',
        'check_timetable_conflicts'   => 'action_check_timetable_conflicts',
        'bulk_notify_parents'         => 'action_bulk_notify_parents',
        'batch_generate_report_pdfs'  => 'action_batch_generate_report_pdfs',
        'create_parent_accounts_bulk' => 'action_create_parent_accounts_bulk',
        'send_whatsapp_broadcast'     => 'action_send_whatsapp_broadcast',
        'deliver_reports_whatsapp'    => 'action_deliver_reports_whatsapp',
        'general_question'            => null,
    ];

    public static function route(string $user_message, string $session_id, int $user_id): array
    {
        $current_term  = rbcGetCurrentTerm();
        $academic_year = getSettingValue('academic_year') ?? date('Y');
        $today         = date('Y-m-d');

        // Step 1: Use AI to classify intent and extract params
        $intent_prompt = <<<PROMPT
You are the RBC AI Agent for EduTrack school management system.
The admin sent this message: "{$user_message}"

Classify the intent and extract parameters.
Available actions:
- send_fee_reminders: params={class_name?, min_balance?}
- generate_terminal_reports: params={class_name, term, academic_year}
- generate_exam_paper: params={subject_name, class_name, term, mcq_count?, theory_count?, fill_blank_count?}
- detect_at_risk_students: params={class_name?, term, academic_year}
- financial_snapshot: params={date_from?, date_to?}
- send_weekly_feeding_summary: params={week_start?, week_end?}
- check_timetable_conflicts: params={academic_year, term}
- bulk_notify_parents: params={target, class_name?, title, message}
- batch_generate_report_pdfs: params={class_name, term, academic_year}
- create_parent_accounts_bulk: params={class_name?}
- send_whatsapp_broadcast: params={target(all|class), class_name?, message}
- deliver_reports_whatsapp: params={class_name, term, academic_year}
- general_question: params={} (for questions that just need an answer)

Return JSON only (no markdown):
{
  "action": "action_name",
  "params": {},
  "confidence": 0.0,
  "clarification_needed": false,
  "clarification_question": ""
}

If confidence < 0.6 or required params are missing, set clarification_needed=true and ask for the missing info.
Current date: {$today}
Current term: {$current_term}
Current academic year: {$academic_year}
PROMPT;

        $intent_result = RBCAIEngine::generate($intent_prompt, '', 600, true);

        if (!$intent_result['success']) {
            return [
                'type'    => 'error',
                'message' => 'AI service temporarily unavailable. Please try again.',
            ];
        }

        // Parse intent
        $raw    = $intent_result['content'];
        $raw    = preg_replace('/^```json\s*/i', '', trim($raw));
        $raw    = preg_replace('/^```\s*/i', '', $raw);
        $raw    = preg_replace('/\s*```$/', '', $raw);
        $intent = json_decode(trim($raw), true);

        if (!$intent || empty($intent['action'])) {
            return [
                'type'    => 'error',
                'message' => 'Could not understand that request. Please rephrase.',
            ];
        }

        // Step 2: If clarification needed
        if (!empty($intent['clarification_needed'])) {
            self::logChat($session_id, $user_id, 'user',      $user_message, null, null);
            self::logChat($session_id, $user_id, 'assistant', $intent['clarification_question'], $intent_result['provider'], null);
            return [
                'type'    => 'clarification',
                'message' => $intent['clarification_question'],
            ];
        }

        // Step 3: Handle general questions
        if ($intent['action'] === 'general_question') {
            $answer = self::answerGeneralQuestion($user_message);
            self::logChat($session_id, $user_id, 'user',      $user_message, null, null);
            self::logChat($session_id, $user_id, 'assistant', $answer, $intent_result['provider'], 'general_question');
            return ['type' => 'answer', 'message' => $answer, 'provider' => $intent_result['provider']];
        }

        // Step 4: Execute the action
        $action_fn = self::$action_map[$intent['action']] ?? null;
        if (!$action_fn || !function_exists($action_fn)) {
            return ['type' => 'error', 'message' => 'Action not available: ' . $intent['action']];
        }

        // Log task start
        global $conn;
        if (!$conn) $conn = getDBConnection();
        $task_type  = $intent['action'];
        $payload    = json_encode($intent['params'] ?? []);
        $task_stmt  = $conn->prepare(
            "INSERT INTO ai_tasks (task_type, payload, status, triggered_by, created_by, started_at)
             VALUES (?,?,'running','chat',?,NOW())"
        );
        $task_stmt->bind_param('ssi', $task_type, $payload, $user_id);
        $task_stmt->execute();
        $task_id = (int) $conn->insert_id;

        // Run action
        $action_result = $action_fn($intent['params'] ?? []);

        // Update task record
        $result_json = json_encode($action_result);
        $status      = $action_result['success'] ? 'completed' : 'failed';
        $upd_stmt    = $conn->prepare(
            "UPDATE ai_tasks SET status=?, result=?, provider_used=?, completed_at=NOW() WHERE id=?"
        );
        $upd_stmt->bind_param('sssi', $status, $result_json, $intent_result['provider'], $task_id);
        $upd_stmt->execute();

        // Generate human-readable response
        $response_text = self::formatActionResponse($intent['action'], $action_result);

        self::logChat($session_id, $user_id, 'user',      $user_message, null, null);
        self::logChat($session_id, $user_id, 'assistant', $response_text, $intent_result['provider'], $intent['action']);

        return [
            'type'     => 'action_result',
            'message'  => $response_text,
            'action'   => $intent['action'],
            'result'   => $action_result,
            'task_id'  => $task_id,
            'provider' => $intent_result['provider'],
        ];
    }

    private static function answerGeneralQuestion(string $question): string
    {
        global $conn;
        if (!$conn) $conn = getDBConnection();

        $stats = [];
        try {
            $r = $conn->query("SELECT COUNT(*) as n FROM students WHERE status='active'");
            $stats['active_students'] = $r ? (int) $r->fetch_assoc()['n'] : 0;
            $r = $conn->query("SELECT COUNT(*) as n FROM staff WHERE status='active'");
            $stats['active_staff'] = $r ? (int) $r->fetch_assoc()['n'] : 0;
            $r = $conn->query("SELECT COALESCE(SUM(amount_paid),0) as n FROM payments WHERE MONTH(payment_date)=MONTH(NOW())");
            $stats['collections_this_month'] = $r ? (float) $r->fetch_assoc()['n'] : 0;
        } catch (Throwable $e) {
            $stats = [];
        }

        $school_name = getSettingValue('school_name') ?: 'the school';
        $result = RBCAIEngine::generate(
            "Answer this admin question about our school: \"{$question}\"\n" .
            "Current system stats: " . json_encode($stats) . "\n" .
            "School name: {$school_name}. Today: " . date('Y-m-d') . "\n" .
            "Give a direct, helpful answer in 2-4 sentences.",
            "You are RBC AI, an intelligent assistant for EduTrack school management system. Be concise and helpful."
        );

        return $result['success']
            ? $result['content']
            : 'I could not process that question right now. Please try again.';
    }

    private static function formatActionResponse(string $action, array $result): string
    {
        if (!$result['success']) {
            return 'I encountered an error: ' . ($result['error'] ?? 'Unknown error');
        }

        $m = [
            'send_fee_reminders' =>
                "Done. Fee reminders sent to " . ($result['sent_count'] ?? 0) . " parents." .
                (($result['failed_count'] ?? 0) > 0 ? " " . ($result['failed_count'] ?? 0) . " could not be reached." : ""),

            'generate_terminal_reports' =>
                "Terminal reports generated for " . ($result['reports_generated'] ?? 0) . " students in " .
                ($result['class_name'] ?? '') . ", " . ($result['term'] ?? '') . "." .
                (($result['skipped'] ?? 0) > 0 ? " " . ($result['skipped'] ?? 0) . " skipped (no scores recorded)." : ""),

            'generate_exam_paper' =>
                "Exam paper created: \"" . ($result['paper_title'] ?? 'Untitled') . "\". " .
                ($result['questions_generated'] ?? 0) . " questions generated by AI, " .
                ($result['questions_from_bank'] ?? 0) . " from question bank. " .
                "Provider: " . ($result['provider_used'] ?? 'AI') . ".",

            'detect_at_risk_students' =>
                "Analysis complete. " . ($result['total_analyzed'] ?? 0) . " students analyzed. " .
                ($result['high_risk'] ?? 0) . " high risk, " . ($result['medium_risk'] ?? 0) . " medium risk.",

            'financial_snapshot' => $result['summary_text'] ?? 'Financial snapshot complete.',

            'check_timetable_conflicts' =>
                count($result['conflicts'] ?? []) . " conflict(s) found. " .
                count($result['ai_suggestions'] ?? []) . " AI suggestion(s) generated. " .
                ($result['empty_slots'] ?? 0) . " empty/incomplete slot(s).",

            'bulk_notify_parents' =>
                "Notifications sent to " . ($result['notified_count'] ?? 0) . " parents." .
                (!empty($result['sms_sent']) ? " {$result['sms_sent']} SMS also sent." : ""),

            'batch_generate_report_pdfs' =>
                ($result['pdf_count'] ?? 0) . " report PDF(s) generated. " .
                (!empty($result['download_url'])
                    ? "<a href='{$result['download_url']}' class='btn btn-sm btn-success mt-1' target='_blank'>" .
                      "<i class='fas fa-download me-1'></i>Download ZIP</a>"
                    : ""),

            'create_parent_accounts_bulk' =>
                ($result['accounts_created'] ?? 0) . " parent account(s) created. " .
                ($result['already_existed'] ?? 0) . " already existed. " .
                ($result['sms_sent'] ?? 0) . " welcome SMS sent.",

            'send_weekly_feeding_summary' =>
                "Weekly feeding summary sent to " . ($result['notifications_sent'] ?? 0) . " parent(s) for " .
                ($result['week_start'] ?? '') . " to " . ($result['week_end'] ?? '') . ".",
        ];

        return $m[$action] ?? 'Action completed successfully.';
    }

    private static function logChat(
        string $session_id, int $user_id, string $role,
        string $message, ?string $provider, ?string $action
    ): void {
        global $conn;
        if (!$conn) $conn = getDBConnection();
        $stmt = $conn->prepare(
            "INSERT INTO ai_chat_logs
             (session_id, user_id, role, message, provider_used, action_taken, created_at)
             VALUES (?,?,?,?,?,?,NOW())"
        );
        if ($stmt) {
            $stmt->bind_param('sissss', $session_id, $user_id, $role, $message, $provider, $action);
            $stmt->execute();
        }
    }
}
