"""Concrete disposable weekly authority backed by real profile stores."""

from __future__ import annotations

import hashlib
import json
import os
import stat
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Final, final, override

from checkin_cli.customer_coaching import (
    CustomerRegistry,
    CustomerRuntime,
    load_customer_registry,
)
from checkin_cli.store import CanonicalEventTransaction
from checkin_cli.weekly_operations import CustomerKey
from checkin_cli.weekly_operations_authority import (
    AuthorityId,
    WeeklyOperationsAuthorityRoot,
    begin_authority_initialization,
)
from checkin_cli.weekly_operations_customer_authority import (
    CanonicalCheckinCustomerAuthority,
)
from checkin_cli.weekly_operations_parent import acquire_parent_authority
from checkin_cli.weekly_operations_registration_handoff import (
    begin_canonical_authority_registration,
)
from checkin_cli.weekly_operations_store import WeeklyOperationsStore
from gateway.platforms.nutrition_weekly_operations_authority import (
    WeeklyOperationsRuntimeContext,
    parse_weekly_operations_authority,
)
from gateway.platforms.nutrition_weekly_operations_config import (
    JsonValue,
    parse_weekly_operations_config,
)
from gateway.platforms.nutrition_weekly_operations_registry_identity import (
    WeeklyOperationsRegistryIdentity,
    parse_weekly_operations_registry_identity,
)
from gateway.platforms.nutrition_weekly_reminder_authority import (
    RegisteredWeeklyReminderCustomer,
    WeeklyReminderAuthorityOwner,
    WeeklyReminderContextSource,
    WeeklyReminderOwnerInput,
    register_weekly_reminder_customer,
)
from gateway.platforms.nutrition_weekly_reminder_owner_factory import (
    weekly_reminder_consent_digest,
)

CANDIDATE: Final = "a" * 64
REGISTRY_DIGEST: Final = "c" * 64
CUSTOMER_KEY: Final = "client_001"


@final
class DisposableContextSource(WeeklyReminderContextSource):
    """Return one immutable runtime context for the synthetic window."""

    @override
    def consent_digest(self, runtime: CustomerRuntime) -> str:
        return weekly_reminder_consent_digest(runtime)

    @override
    def current_context(
        self, runtime: CustomerRuntime, now: datetime,
    ) -> WeeklyOperationsRuntimeContext:
        return WeeklyOperationsRuntimeContext(
            CANDIDATE, runtime.spec.customer_key, "100", "100", 7,
            weekly_reminder_consent_digest(runtime), True,
            "weekly-operations-v1", now,
        )


class WeeklyAuthorityFixtureError(RuntimeError):
    """Disposable weekly authority construction failed closed."""


@dataclass(frozen=True, slots=True)
class WeeklyAuthorityFixture:
    registry: CustomerRegistry
    owner: WeeklyReminderAuthorityOwner
    customer: RegisteredWeeklyReminderCustomer
    store: WeeklyOperationsStore
    runtime: CustomerRuntime
    extra: dict[str, JsonValue]


def _registry_payload() -> dict[str, JsonValue]:
    weeks: list[JsonValue] = [
        {
            "week": week, "calories_kcal": 2300, "protein_g": 150,
            "meal_structure": ["breakfast", "lunch", "dinner"],
        }
        for week in range(1, 13)
    ]
    return {
        "version": 1,
        "owner": {"user_id": "100", "chat_id": "100", "topic_id": "0"},
        "customers": [{
            "customer_key": CUSTOMER_KEY, "display_name": "fixture", "enabled": True,
            "telegram": {"user_id": "300", "chat_id": "300", "topic_id": "41"},
            "schedule": {"daily_time": "08:00", "weekly_weekday": 0, "monthly_day": 1},
            "profile": {"primary_goal": "fixture", "sleep_goal_hours": 8},
            "ai_processing_consent": {
                "granted": True, "recorded_on": "2026-08-01",
                "notice_version": "privacy-v1",
            },
            "plan": {
                "starts_on": "2026-08-01", "focus": "nutrition_90_training_10",
                "weeks": weeks,
            },
        }],
    }


def _registry_identity(root: Path, relative_name: str) -> WeeklyOperationsRegistryIdentity:
    path = root / relative_name
    info = path.stat()
    if (
        not stat.S_ISREG(info.st_mode)
        or stat.S_IMODE(info.st_mode) != 0o600
        or info.st_uid != os.geteuid()
        or info.st_nlink != 1
    ):
        raise WeeklyAuthorityFixtureError("disposable registry identity is unsafe")
    values: dict[str, str | int] = {
        "schema_version": "nutricoach-weekly-registry-identity-v1",
        "relative_name": relative_name,
        "device": info.st_dev,
        "inode": info.st_ino,
        "mode": stat.S_IMODE(info.st_mode),
        "owner": info.st_uid,
        "links": info.st_nlink,
        "content_digest": hashlib.sha256(path.read_bytes()).hexdigest(),
    }
    encoded = json.dumps(values, sort_keys=True, separators=(",", ":")).encode()
    values["binding_digest"] = hashlib.sha256(encoded).hexdigest()
    return parse_weekly_operations_registry_identity(values)


def create_weekly_authority(root: Path) -> WeeklyAuthorityFixture:
    """Create one real registry, canonical store, sidecar, and authority owner."""
    root.mkdir(parents=True, mode=0o700)
    registry_path = root / "registry.json"
    _ = registry_path.write_text(json.dumps(_registry_payload()), encoding="utf-8")
    registry_path.chmod(0o600)
    identity = _registry_identity(root, "registry.json")
    registry = load_customer_registry(registry_path, root)
    runtime = registry.customers[0]
    authority_path = root / "weekly-authority"
    authority_path.mkdir(mode=0o700)
    parent = acquire_parent_authority(authority_path)
    authority: WeeklyOperationsAuthorityRoot | None = None
    with begin_authority_initialization(parent, AuthorityId("4" * 64)) as initialization:
        authority = initialization.authority
        _ = initialization.binding
        initialization.acknowledge_binding()
    if authority is None:
        raise WeeklyAuthorityFixtureError("weekly authority initialization failed")
    store = WeeklyOperationsStore.for_authority(authority, CustomerKey(CUSTOMER_KEY))
    for path in (runtime.customer_root, runtime.wizard_root, runtime.nutrition_plans_root):
        path.mkdir(parents=True, mode=0o700)
    transaction = CanonicalEventTransaction.for_customer_runtime(runtime)
    for path in (transaction.events_path, transaction.sequence_path):
        path.touch(mode=0o600)
        path.chmod(0o600)
    _ = transaction.read_snapshot()
    canonical: CanonicalCheckinCustomerAuthority | None = None
    with begin_canonical_authority_registration(runtime, authority) as registration:
        canonical = registration.authority
        _ = registration.binding
        registration.acknowledge_binding()
    if canonical is None:
        raise WeeklyAuthorityFixtureError("canonical authority registration failed")
    customer = register_weekly_reminder_customer(runtime, canonical, store)
    nutrition_config: dict[str, JsonValue] = {
        "operator_review": {"user_id": "100", "chat_id": "200", "topic_id": 59},
        "weekly_operations": {
            "enabled": True, "reminder_time": "20:00:00",
            "missed_cutoff_time": "23:00:00", "weekly_weekday": 0,
            "feature_epoch": "weekly-operations-v1",
            "registry_identity_binding_digest": identity.binding_digest,
        },
    }
    base: dict[str, JsonValue] = {"nutrition_coaching": nutrition_config}
    config = parse_weekly_operations_config(base)
    identity_document: dict[str, JsonValue] = {
        "schema_version": identity.schema_version,
        "relative_name": identity.relative_name,
        "device": identity.device,
        "inode": identity.inode,
        "mode": identity.mode,
        "owner": identity.owner,
        "links": identity.links,
        "content_digest": identity.content_digest,
        "binding_digest": identity.binding_digest,
    }
    receipt_document: dict[str, JsonValue] = {
        "schema": "nutricoach-weekly-operations-authority-v2",
        "candidate_digest": CANDIDATE, "config_digest": config.digest,
        "enabled_customer_keys": [CUSTOMER_KEY],
        "owner": {"user_id": "100", "chat_id": "100", "version": 7},
        "consent_digest": weekly_reminder_consent_digest(runtime),
        "registry_identity": identity_document,
        "issued_at": "2026-08-17T19:00:00+09:00",
        "expires_at": "2026-08-30T23:59:00+09:00",
        "feature_epoch": "weekly-operations-v1",
    }
    receipt = parse_weekly_operations_authority(receipt_document)
    extra = dict(base)
    nutrition = dict(nutrition_config)
    nutrition["weekly_operations_authority"] = receipt_document
    nutrition["weekly_operations_authority_source"] = "operator"
    extra["nutrition_coaching"] = nutrition
    owner = WeeklyReminderAuthorityOwner(WeeklyReminderOwnerInput(
        config, receipt, REGISTRY_DIGEST, (customer,), DisposableContextSource(),
    ))
    return WeeklyAuthorityFixture(registry, owner, customer, store, runtime, extra)
