from __future__ import annotations

from .grader import FeatureGrader
from .lesson import build_lesson_steps
from .models import LearningSession, SessionMode, SkillStep, StandardAnswer, StepCompareResult


class SessionStore:
    def __init__(self) -> None:
        self._items: dict[str, LearningSession] = {}

    def start(self, mode: SessionMode, standard: StandardAnswer) -> LearningSession:
        session = LearningSession(
            mode=mode,
            standard_id=standard.standard_id,
            title=standard.title,
            lesson_steps=build_lesson_steps(standard),
        )
        self._items[session.session_id] = session
        return session

    def require(self, session_id: str) -> LearningSession:
        if session_id not in self._items:
            raise KeyError(f"session not found: {session_id}")
        return self._items[session_id]


class LearningService:
    def __init__(self, store: SessionStore, grader: FeatureGrader) -> None:
        self.store = store
        self.grader = grader

    def submit_teaching_observation(self, session_id: str, observed: list[SkillStep]) -> StepCompareResult:
        session = self.store.require(session_id)
        session.observed_steps.extend(observed)
        expected = session.lesson_steps[session.current_step_index] if session.current_step_index < len(session.lesson_steps) else None
        if expected is None:
            session.status = "completed"
            result = StepCompareResult(ok=True, score=100, feedback_text="教学步骤已经完成。")
            session.reports.append(result)
            return result
        actual = observed[-1] if observed else None
        result = self.grader.compare_step(expected, actual)
        session.reports.append(result)
        if result.ok:
            session.current_step_index += 1
            if session.current_step_index >= len(session.lesson_steps):
                session.status = "completed"
        return result

    def submit_test(self, session_id: str, observed: list[SkillStep]):
        session = self.store.require(session_id)
        session.observed_steps = observed
        report = self.grader.grade_sequence(session.lesson_steps, observed)
        session.final_report = report
        session.status = "completed"
        return report

