"""
fw_server/grade_map.py — Map verification pass-counts to EpistemicGrade.

Governing axioms:
  AX56: Max achievable grade = İlmelyakîn; Hakkalyakîn permanently inaccessible.
  T15:  Structural claims (külliyat) > detail claims (tafsîlât).
  §5.3: Epistemic degree scale: Tasavvur < Tasdik < İlmelyakîn.

The mapping is deliberately conservative: the framework must NOT
over-claim certainty.  The thresholds are calibrated so that even
a perfect formal instrument never crosses into Hakkalyakîn.
"""

from __future__ import annotations

from bileshke.types import EpistemicGrade


# ── Threshold boundaries (inclusive lower bound) ──
# 0.00 – 0.60  → TASAVVUR   (conceptual grasp)
# 0.61 – 0.85  → TASDIK     (affirmative judgment)
# 0.86 – 1.00  → ILMELYAKIN (knowledge-certainty — TARGET grade)
# Hakkalyakîn is NEVER returned (AX56).

_GRADE_THRESHOLDS: list[tuple[float, EpistemicGrade]] = [
    (0.86, EpistemicGrade.ILMELYAKIN),
    (0.61, EpistemicGrade.TASDIK),
    (0.00, EpistemicGrade.TASAVVUR),
]


def score_to_grade(score: float) -> EpistemicGrade:
    """Convert a yakinlasma score ∈ [0, 1) to an EpistemicGrade.

    >>> score_to_grade(0.92)
    <EpistemicGrade.ILMELYAKIN: 'İlmelyakîn'>
    >>> score_to_grade(0.70)
    <EpistemicGrade.TASDIK: 'Tasdik'>
    >>> score_to_grade(0.30)
    <EpistemicGrade.TASAVVUR: 'Tasavvur'>
    """
    clamped = min(max(score, 0.0), 0.9999)
    for threshold, grade in _GRADE_THRESHOLDS:
        if clamped >= threshold:
            return grade
    return EpistemicGrade.TASAVVUR


def pass_ratio_to_grade(passed: int, total: int) -> EpistemicGrade:
    """Convert a checks-passed / checks-total ratio to an EpistemicGrade.

    >>> pass_ratio_to_grade(9, 10)
    <EpistemicGrade.ILMELYAKIN: 'İlmelyakîn'>
    >>> pass_ratio_to_grade(7, 10)
    <EpistemicGrade.TASDIK: 'Tasdik'>
    >>> pass_ratio_to_grade(3, 10)
    <EpistemicGrade.TASAVVUR: 'Tasavvur'>
    >>> pass_ratio_to_grade(0, 0)
    <EpistemicGrade.TASAVVUR: 'Tasavvur'>
    """
    if total <= 0:
        return EpistemicGrade.TASAVVUR
    ratio = passed / total
    return score_to_grade(ratio)


def grade_to_string(grade: EpistemicGrade) -> str:
    """Get the display string for an EpistemicGrade.

    >>> grade_to_string(EpistemicGrade.ILMELYAKIN)
    'İlmelyakîn'
    """
    return grade.value
