<?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 ASSIGNMENT SCORES\n";

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

$rows=
$db->query("
SELECT
rp.*,
COALESCE(rws.utilization_percent,0)
AS workload_percent
FROM reviewer_performance rp
LEFT JOIN reviewer_workload_status rws
ON rws.reviewer_id=rp.reviewer_id
AND rws.conference_id=rp.conference_id
")->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $r){

    $expertise=
    (float)($r['expertise_score'] ?? 50);

    $performance=
    (float)($r['final_score'] ?? 0);

    $capacity=
    100 -
    (float)($r['workload_percent'] ?? 0);

    $deadline=
    (float)($r['completion_rate'] ?? 0);

    $riskPenalty=0;

    if(
        $performance < 40
    ){
        $riskPenalty=30;
    }

    $workloadPenalty=0;

    if(
        (float)($r['workload_percent'] ?? 0)
        > 80
    ){
        $workloadPenalty=25;
    }

    $final=
    $expertise * 0.20
    +
    $performance * 0.35
    +
    $capacity * 0.20
    +
    $deadline * 0.25
    -
    $riskPenalty
    -
    $workloadPenalty;

    $db->prepare("
    INSERT INTO reviewer_assignment_scores
    (
        conference_id,
        reviewer_id,
        expertise_score,
        performance_score,
        capacity_score,
        deadline_score,
        risk_penalty,
        workload_penalty,
        final_assignment_score
    )
    VALUES
    (
        ?,?,?,?,?,?,?,?,?
    )
    ")->execute([
        $r['conference_id'],
        $r['reviewer_id'],
        $expertise,
        $performance,
        $capacity,
        $deadline,
        $riskPenalty,
        $workloadPenalty,
        $final
    ]);

}

echo "DONE\n";
