<?php

namespace App\Services\Scores;

use App\Models\Configuration;

class ScoreTermService
{
    public function normalizeSemester(?string $input): string
    {
        $value = strtolower(trim((string) $input));
        if ($value === 'fall' || str_contains($value, '1')) {
            return 'fall';
        }
        if ($value === 'spring' || str_contains($value, '2')) {
            return 'spring';
        }
        return '';
    }

    public function semesterLabel(?string $input, ?string $fallback = null): string
    {
        $normalized = $this->normalizeSemester($input);
        if ($normalized !== '') {
            return ucfirst($normalized);
        }
        if ($fallback && trim($fallback) !== '') {
            return (string) $fallback;
        }

        return (string) (Configuration::getConfig('semester') ?? 'Fall');
    }

    public function schoolYear(?string $input, ?string $fallback = null): string
    {
        $value = trim((string) $input);
        if ($value !== '') {
            return $value;
        }
        if ($fallback && trim($fallback) !== '') {
            return (string) $fallback;
        }

        return (string) (Configuration::getConfig('school_year') ?? '');
    }

    public function semesterVariants(?string $semester): array
    {
        $raw = trim((string) $semester);
        $variants = [
            $raw,
            strtolower($raw),
            ucfirst(strtolower($raw)),
        ];
        $normalized = $this->normalizeSemester($raw);
        if ($normalized === 'fall') {
            $variants[] = 'First Semester';
            $variants[] = 'Semester 1';
            $variants[] = '1st Semester';
            $variants[] = 'Fall Semester';
        } elseif ($normalized === 'spring') {
            $variants[] = 'Second Semester';
            $variants[] = 'Semester 2';
            $variants[] = '2nd Semester';
            $variants[] = 'Spring Semester';
        }

        return array_values(array_unique(array_filter($variants, static fn ($v) => $v !== '')));
    }
}
