<?php
/**
 * Action: Detect at-risk students based on scores and fees, with AI risk analysis.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../provider_engine.php';
require_once __DIR__ . '/../fee_balance.php';

function action_detect_at_risk_students(array $params): array
{
    $conn            = getDBConnection();
    $class_name      = $params['class_name'] ?? null;
    $term            = $params['term'] ?? getSettingValue('current_term') ?? 'First Term';
    $academic_year   = $params['academic_year'] ?? getSettingValue('academic_year') ?? date('Y');
    $score_threshold = (float) ($params['score_threshold'] ?? 50);
    $fee_threshold   = (float) ($params['fee_threshold'] ?? 100);

    // 1. Students with low average scores
    $score_sql = "SELECT s.id, s.first_name, s.last_name, s.class,
                         AVG(sr.total_score) AS avg_score
                  FROM students s
                  JOIN scores sr ON sr.student_id = s.id
                  WHERE sr.term = ? AND sr.academic_year = ? AND s.status = 'active'";
    $score_types = 'ss';
    $score_binds = [$term, $academic_year];
    if (!empty($class_name)) {
        $score_sql  .= " AND s.class = ?";
        $score_types .= 's';
        $score_binds[] = $class_name;
    }
    $score_sql .= " GROUP BY s.id HAVING avg_score < ?";
    $score_types .= 'd';
    $score_binds[] = $score_threshold;

    $stmt = $conn->prepare($score_sql);
    $stmt->bind_param($score_types, ...$score_binds);
    $stmt->execute();
    $low_scorers = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    // 2. Students with high fee balances. Pre-aggregated on both sides — see
    //    ai/fee_balance.php. The previous inline join double-counted a fee for
    //    every extra instalment, flagging students who were not actually behind.
    $high_fee = rbcOutstandingBalances($conn, $academic_year, $class_name, $fee_threshold);

    // Build combined dataset for AI
    $all_students = [];
    $seen         = [];
    foreach ($low_scorers as $s) {
        $seen[$s['id']] = true;
        $all_students[] = [
            'student_id'   => $s['id'],
            'student_name' => $s['first_name'] . ' ' . $s['last_name'],
            'class'        => $s['class'],
            'avg_score'    => round((float) $s['avg_score'], 1),
            'fee_balance'  => 0,
            'risk_factors' => ['Low academic performance'],
        ];
    }
    foreach ($high_fee as $s) {
        if (isset($seen[$s['id']])) {
            // Add fee risk to existing record
            foreach ($all_students as &$st) {
                if ($st['student_id'] === $s['id']) {
                    $st['fee_balance']  = (float) $s['balance'];
                    $st['risk_factors'][] = 'High fee balance';
                }
            }
            unset($st);
        } else {
            $all_students[] = [
                'student_id'   => $s['id'],
                'student_name' => $s['first_name'] . ' ' . $s['last_name'],
                'class'        => $s['class'],
                'avg_score'    => null,
                'fee_balance'  => (float) $s['balance'],
                'risk_factors' => ['High fee balance'],
            ];
        }
    }

    if (empty($all_students)) {
        return [
            'success'          => true,
            'at_risk_students' => [],
            'total_analyzed'   => 0,
            'high_risk'        => 0,
            'medium_risk'      => 0,
        ];
    }

    // 3. Use AI to classify risk
    $ai_result = RBCAIEngine::generate(
        "Analyze these student records and identify at-risk students. " .
        "For each, give a risk_level (high/medium/low) and a recommended_action (max 20 words). " .
        "Students data: " . json_encode(array_slice($all_students, 0, 30)) . "\n" .
        "Return JSON array: [{\"student_id\":N,\"student_name\":\"...\",\"risk_level\":\"high|medium|low\"," .
        "\"risk_factors\":[],\"recommended_action\":\"...\"}]",
        "You are a school counsellor assistant analyzing student at-risk data.",
        2000,
        true
    );

    $at_risk = $all_students; // default: use raw data

    if ($ai_result['success']) {
        $raw = preg_replace('/^```json\s*/i', '', trim($ai_result['content']));
        $raw = preg_replace('/^```\s*/i', '', $raw);
        $raw = preg_replace('/\s*```$/', '', $raw);
        $parsed = json_decode(trim($raw), true);
        if (is_array($parsed)) {
            $at_risk = $parsed;
        }
    }

    $high_risk   = count(array_filter($at_risk, fn($s) => ($s['risk_level'] ?? '') === 'high'));
    $medium_risk = count(array_filter($at_risk, fn($s) => ($s['risk_level'] ?? '') === 'medium'));

    return [
        'success'          => true,
        'at_risk_students' => $at_risk,
        'total_analyzed'   => count($at_risk),
        'high_risk'        => $high_risk,
        'medium_risk'      => $medium_risk,
    ];
}
