"""Current-authority checks for onboarding mutations."""

from __future__ import annotations

from pathlib import Path

from checkin_cli.customer_coaching import load_customer_registry
from checkin_cli.nutrition_onboarding_contract import (
    MessageEvidence,
    OnboardingAuthority,
)
from checkin_cli.nutrition_onboarding_models import NutritionOnboardingBaseline


def validate_authority(authority: OnboardingAuthority, *, customer_key: str) -> None:
    if authority.customer_key != customer_key:
        raise ValueError("customer authority mismatch")
    if not authority.consent_granted or authority.consent_notice_version != "privacy-v1":
        raise ValueError("current privacy-v1 consent is required")
    if authority.customer_enabled:
        raise ValueError("onboarding target must remain disabled")


def validate_route(
    authority: OnboardingAuthority,
    evidence: MessageEvidence,
    *,
    role: str,
) -> None:
    expected = (
        getattr(authority, f"{role}_user_id"),
        getattr(authority, f"{role}_chat_id"),
        getattr(authority, f"{role}_topic_id"),
    )
    actual = (evidence.actor_user_id, evidence.chat_id, evidence.topic_id)
    if actual != expected:
        raise ValueError(f"{role} route does not match")


def validate_current_registry_authority(
    profile_root: Path,
    authority: OnboardingAuthority,
) -> None:
    root = Path(profile_root)
    registry = load_customer_registry(
        root / "customers" / "registry.json",
        root,
    )
    matches = [
        customer
        for customer in registry.customers
        if customer.spec.customer_key == authority.customer_key
    ]
    if len(matches) != 1:
        raise ValueError("current onboarding customer authority is unavailable")
    customer = matches[0].spec
    if (
        customer.enabled
        or not customer.ai_processing_consent.granted
        or customer.ai_processing_consent.notice_version != "privacy-v1"
    ):
        raise ValueError("current onboarding consent or state is invalid")
    expected = (
        customer.telegram.key,
        registry.owner.key,
    )
    actual = (
        tuple(str(value) for value in (
            authority.customer_user_id,
            authority.customer_chat_id,
            authority.customer_topic_id,
        )),
        tuple(str(value) for value in (
            authority.owner_user_id,
            authority.owner_chat_id,
            authority.owner_topic_id,
        )),
    )
    if actual != expected:
        raise ValueError("current onboarding routes have changed")


def requires_safety_hold(baseline: NutritionOnboardingBaseline) -> bool:
    return (
        baseline.conditions.status.value == "provided"
        or baseline.medications.status.value == "provided"
        or baseline.pregnancy_breastfeeding is not False
        or baseline.eating_disorder_risk is not False
    )
