<?php

namespace App\Services\Scores;

use App\Models\Configuration;

class ScorePredictorService
{
    public function __construct(
        private ScorePredictorDataService $dataService,
        private ScorePredictorRiskService $riskService
    ) {
    }

    public function report(?string $schoolYear, ?int $classSectionId = null): array
    {
        $currentSchoolYear = (string) (Configuration::getConfig('school_year') ?? '');
        $semester = (string) (Configuration::getConfig('semester') ?? '');
        $targetTrophy = (float) (Configuration::getConfig('trophy_score') ?? 94.0);
        $targetLow = (float) (Configuration::getConfig('pass_score') ?? 60.0);

        $selectedYear = $schoolYear ?: $currentSchoolYear;
        $classSections = $this->dataService->classSections($selectedYear);
        $students = $this->dataService->students($selectedYear, $classSectionId);

        $stats = $this->dataService->springStats($selectedYear, $classSectionId);
        $mean = (float) ($stats['mean'] ?? 70.0);
        $std = (float) ($stats['std'] ?? 0.0);

        $trophyThreshold = max(94.0, $targetTrophy);
        $results = $this->riskService->evaluate($students, $mean, $std, $trophyThreshold, $targetLow);

        return [
            'students' => $results,
            'school_year' => $selectedYear,
            'class_sections' => $classSections,
            'selected_class_section_id' => $classSectionId,
            'semester' => $semester,
        ];
    }
}
