"""Sealed finite renderer for one authority-bound weekly owner source."""

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field
from typing import Final, Literal, TypeAlias

from .weekly_operations_grounding_types import (
    FALLBACK_TOKEN,
    LOCK_TOKEN,
    GroundedWeeklyFacts,
    WeeklyGroundingError,
)
from .weekly_operations_knowledge import (
    WeeklyEmphasis,
    WeeklyPrincipleId,
    load_shipped_weekly_public_knowledge,
)

CanonicalValue: TypeAlias = str | bool | tuple["CanonicalValue", ...]


class _SourceSeal:
    __slots__: Final = ()


_SOURCE_SEAL: Final = _SourceSeal()


@dataclass(frozen=True, slots=True, init=False)
class GroundedWeeklyReviewSource:
    source_kind: Literal["grounded_weekly_review"] = field(init=False, default="grounded_weekly_review")
    facts: GroundedWeeklyFacts
    principle_ids: tuple[WeeklyPrincipleId, ...]
    emphasis: WeeklyEmphasis
    fallback_used: bool
    package_digest: str
    template_digest: str
    source_digest: str
    _seal: _SourceSeal

    def __init__(self, facts: GroundedWeeklyFacts, principle_ids: tuple[WeeklyPrincipleId, ...], emphasis: WeeklyEmphasis, fallback_used: bool, package_digest: str, template_digest: str, source_digest: str, _seal: _SourceSeal) -> None:
        values = ("grounded_weekly_review", facts, principle_ids, emphasis, fallback_used, package_digest, template_digest, source_digest, _seal)
        for name, value in zip(self.__slots__, values, strict=True):
            object.__setattr__(self, name, value)

    def verify(self) -> bool:
        if self._seal is not _SOURCE_SEAL or not self.facts.verify() or not self.principle_ids:
            return False
        try:
            return self == build_grounded_weekly_source(
                self.facts, self.principle_ids, self.emphasis,
                fallback_used=self.fallback_used,
            )
        except WeeklyGroundingError:
            return False

    def render_customer_body(self) -> str:
        if not self.verify():
            raise WeeklyGroundingError("source seal")
        knowledge = load_shipped_weekly_public_knowledge()
        selected = tuple(knowledge.principle(item).template for item in self.principle_ids)
        comparison = self.facts.prior_week_comparison
        compared = "이전 주 자료 없음" if comparison is None else "/".join((
            str(comparison.submitted_count_delta), str(comparison.late_count_delta),
            str(comparison.missed_count_delta), str(comparison.completed_days_delta),
            str(comparison.adherence_percent_delta),
        ))
        facts = (
            FALLBACK_TOKEN if self.fallback_used else LOCK_TOKEN,
            f"기간: {self.facts.starts_on.isoformat()}~{self.facts.ends_on.isoformat()}",
            f"상태: {self.facts.week_status.value}",
            f"제출/지연/미제출: {self.facts.submitted_count}/{self.facts.late_count}/{self.facts.missed_count}",
            f"완료: {self.facts.completed_days}/7 ({self.facts.adherence_percent}%)",
            f"추세: {self.facts.weight_trend.value}",
            f"리마인더 전송/사고: {self.facts.reminder_sent_count}/{self.facts.reminder_incident_count}",
            f"이전 주 비교: {compared}",
            f"결정 선택지: {', '.join(item.value for item in self.facts.decision_options)}",
            f"결정: {self.facts.decision.value}",
            f"소유자 행동: {', '.join(item.value for item in self.facts.actions)}",
        )
        ordered = (*selected, *facts) if self.emphasis is WeeklyEmphasis.LIMITS_FIRST else (*facts, *selected)
        return "\n".join(ordered)


def build_grounded_weekly_source(facts: GroundedWeeklyFacts, principle_ids: tuple[WeeklyPrincipleId, ...], emphasis: WeeklyEmphasis, *, fallback_used: bool = False) -> GroundedWeeklyReviewSource:
    knowledge = load_shipped_weekly_public_knowledge()
    if not facts.verify() or not 1 <= len(principle_ids) <= 2 or len(set(principle_ids)) != len(principle_ids):
        raise WeeklyGroundingError("source fields")
    templates = tuple(knowledge.principle(item).template for item in principle_ids)
    template_digest = hashlib.sha256(_canonical((emphasis.value, templates, fallback_used))).hexdigest()
    source_digest = hashlib.sha256(_canonical((facts.grounding_digest, tuple(item.value for item in principle_ids), emphasis.value, fallback_used, knowledge.package_digest, template_digest))).hexdigest()
    return GroundedWeeklyReviewSource(facts, principle_ids, emphasis, fallback_used, knowledge.package_digest, template_digest, source_digest, _SOURCE_SEAL)


def deterministic_weekly_fallback(facts: GroundedWeeklyFacts) -> GroundedWeeklyReviewSource:
    return build_grounded_weekly_source(
        facts, (WeeklyPrincipleId.OWNER_DECIDES,),
        WeeklyEmphasis.SUMMARY_FIRST, fallback_used=True,
    )


def _canonical(value: CanonicalValue) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
