<?php

define(
'BASE_PATH',
realpath(__DIR__.'/../..')
);

require_once BASE_PATH.'/config/autoload.php';
require_once BASE_PATH.'/config/bootstrap.php';

$db=\App\Core\Database::getInstance();

echo "AI OPERATIONS CENTER\n";

$db->exec(
"TRUNCATE TABLE ai_operations_center"
);

$confs=
$db->query("
SELECT id
FROM conferences
")->fetchAll(PDO::FETCH_ASSOC);

foreach($confs as $c){

    $cid=(int)$c['id'];

    $conf=
    (float)$db->query("
    SELECT
    COALESCE(MAX(overall_health_score),0)
    FROM conference_health_metrics
    WHERE conference_id=".$cid
    )->fetchColumn();

    $reviewer=
    (float)$db->query("
    SELECT
    COALESCE(AVG(final_assignment_score),0)
    FROM reviewer_assignment_scores
    WHERE conference_id=".$cid
    )->fetchColumn();

    $track=
    (float)$db->query("
    SELECT
    COALESCE(AVG(health_score),0)
    FROM track_health_metrics
    WHERE conference_id=".$cid
    )->fetchColumn();

    $risk=
    (float)$db->query("
    SELECT COUNT(*)
    FROM reviewer_risk_flags
    WHERE conference_id=".$cid."
    AND is_active=1
    ")->fetchColumn();

    $assign=
    (float)$db->query("
    SELECT
    COALESCE(AVG(final_assignment_score),0)
    FROM reviewer_assignment_scores
    WHERE conference_id=".$cid
    )->fetchColumn();

    $overall=
    round(
        (
            $conf+
            $reviewer+
            $track+
            max(0,100-$risk)+
            $assign
        )/5,
        2
    );

    $db->prepare("
    INSERT INTO ai_operations_center
    (
        conference_id,
        conference_health_score,
        reviewer_health_score,
        track_health_score,
        risk_score,
        assignment_score,
        overall_ai_score
    )
    VALUES
    (
        ?,?,?,?,?,?,?
    )
    ")->execute([
        $cid,
        $conf,
        $reviewer,
        $track,
        $risk,
        $assign,
        $overall
    ]);

}

echo "DONE\n";
