<?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 "REVIEWER NETWORK REBUILD\n";

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

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

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

$reviewers=
$db->query("
SELECT
reviewer_id,
conference_id,
COUNT(*) review_count
FROM review_assignments
GROUP BY reviewer_id,conference_id
")->fetchAll(PDO::FETCH_ASSOC);

foreach($reviewers as $r){

    $rid=(int)$r['reviewer_id'];
    $cid=(int)$r['conference_id'];

    $perf=
    $db->query("
        SELECT *
        FROM reviewer_performance
        WHERE reviewer_id=".$rid."
        AND conference_id=".$cid."
        LIMIT 1
    ")->fetch(PDO::FETCH_ASSOC);

    $completion=
    (float)($perf['completion_rate'] ?? 0);

    $reviews=
    (int)$r['review_count'];

    $influence=
    round(
        ($reviews*2)
        +
        ($completion*0.5),
        2
    );

    $diversity=
    min(
        100,
        $reviews*5
    );

    $db->prepare("
    INSERT INTO reviewer_network_metrics
    (
        conference_id,
        reviewer_id,
        review_count,
        completion_rate,
        influence_score,
        diversity_score
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ")->execute([
        $cid,
        $rid,
        $reviews,
        $completion,
        $influence,
        $diversity
    ]);

    if($reviews > 20){

        $db->prepare("
        INSERT INTO reviewer_cluster_analysis
        (
            conference_id,
            reviewer_id,
            cluster_name,
            cluster_score
        )
        VALUES
        (
            ?,?,?,?
        )
        ")->execute([
            $cid,
            $rid,
            'High Activity Cluster',
            $reviews
        ]);

    }

    if($reviews > 30){

        $db->prepare("
        INSERT INTO reviewer_bias_alerts
        (
            conference_id,
            reviewer_id,
            alert_type,
            alert_reason,
            alert_score
        )
        VALUES
        (
            ?,?,?,?,?
        )
        ")->execute([
            $cid,
            $rid,
            'review_concentration',
            'Reviewer handles unusually high volume',
            $reviews
        ]);

    }

}

echo "DONE\n";
