#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///

# ─── How to run ───
# 1. Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh
# 2. Use through: uv run python scripts/run_nutricoach_v140_golden_path.py --help
# ──────────────────

"""Disposable production profile and weekly capability authority."""

from __future__ import annotations

import hashlib
import json
import stat
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

from checkin_cli.customer_coaching import CustomerRegistry, load_customer_registry
from checkin_cli.customer_schedule import initialize_schedule_delivery_fence
from checkin_cli.store import CanonicalEventTransaction
from checkin_cli.weekly_operations_authority import AuthorityId, begin_authority_initialization
from checkin_cli.weekly_operations_registration_handoff import begin_canonical_authority_registration
from checkin_cli.weekly_operations_parent import acquire_parent_authority
from gateway.config import PlatformConfig
from scripts.nutricoach_v140_golden_path_models import CliError
from gateway.platforms.nutrition_weekly_operations_config import JsonValue, parse_weekly_operations_config
from gateway.platforms.nutrition_weekly_operations_registry_identity import WeeklyOperationsRegistryIdentity
from gateway.platforms.nutrition_weekly_reminder_owner_factory import weekly_reminder_consent_digest

CANDIDATE = "a" * 64
CUSTOMER = "client_001"


def _registry_document() -> dict[str, JsonValue]:
    return {
        "version": 1,
        "owner": {"user_id": "coach", "chat_id": "owner-dm", "topic_id": "owner"},
        "customers": [{
            "customer_key": CUSTOMER, "display_name": "PRIVACY_RAW_NAME_SENTINEL", "enabled": True,
            "telegram": {"user_id": "client", "chat_id": "customer-chat", "topic_id": "41"},
            "schedule": {"daily_time": "08:00", "weekly_weekday": 0, "monthly_day": 1},
            "profile": {"primary_goal": "PRIVACY_HEALTH_SENTINEL", "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": [
                    {"week": week, "calories_kcal": 2300, "protein_g": 150,
                     "carbohydrate_g": 280, "fat_g": 65,
                     "meal_structure": [
                         "PRIVACY_NUTRITION_SENTINEL", "PRIVACY_FREE_TEXT_SENTINEL", "dinner",
                     ]}
                    for week in range(1, 13)
                ],
            },
        }],
    }


def _identity(path: Path) -> WeeklyOperationsRegistryIdentity:
    info = path.stat(follow_symlinks=False)
    values: dict[str, str | int] = {
        "schema_version": "nutricoach-weekly-registry-identity-v1",
        "relative_name": "registry.json", "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()
    return WeeklyOperationsRegistryIdentity(
        "nutricoach-weekly-registry-identity-v1", "registry.json",
        info.st_dev, info.st_ino, stat.S_IMODE(info.st_mode), info.st_uid,
        info.st_nlink, hashlib.sha256(path.read_bytes()).hexdigest(),
        hashlib.sha256(encoded).hexdigest(),
    )


def _identity_document(identity: WeeklyOperationsRegistryIdentity) -> dict[str, JsonValue]:
    return {
        "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,
    }


def create_profile(root: Path) -> None:
    """Create one disposable profile and register real Todo3/4 capabilities."""
    root.mkdir(mode=0o700)
    registry_path = root / "registry.json"
    _ = registry_path.write_text(
        json.dumps(_registry_document(), ensure_ascii=False, sort_keys=True), encoding="utf-8"
    )
    registry_path.chmod(0o600)
    registry = load_customer_registry(registry_path, root)
    authority_path = root / "weekly-authority"
    authority_path.mkdir(mode=0o700)
    parent = acquire_parent_authority(authority_path)
    authority = None
    with begin_authority_initialization(parent, AuthorityId("4" * 64)) as initialization:
        authority = initialization.authority
        _ = initialization.binding
        initialization.acknowledge_binding()
    if authority is None:
        raise CliError("weekly authority initialization failed")
    runtime = registry.customers[0]
    runtime.customer_root.mkdir(parents=True, mode=0o700)
    runtime.wizard_root.mkdir(parents=True, mode=0o700)
    runtime.nutrition_plans_root.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()
    from gateway.platforms.nutrition_coaching import NutritionCoachingCoordinator
    from scripts.nutricoach_v140_golden_path_owner import seed_owner_snapshot

    owner_now = datetime(2026, 8, 25, 9, tzinfo=ZoneInfo("Asia/Seoul"))
    seed_owner_snapshot(
        NutritionCoachingCoordinator(
            root, registry, registry_path=None,
            kst_date_provider=lambda: owner_now,
            generation_now_provider=lambda: owner_now,
        )
    )
    source = None
    with begin_canonical_authority_registration(runtime, authority) as registration:
        source = registration.authority
        _ = registration.binding
        registration.acknowledge_binding()
    if source is None:
        raise CliError("canonical authority registration failed")
    source.close()
    authority.close()
    parent.close()
    data = root / "data"
    data.mkdir(mode=0o700, exist_ok=True)
    ledger = data / "scheduled-deliveries.jsonl"
    ledger.touch(mode=0o600)
    ledger.chmod(0o600)
    (data / "customer-schedule-claims").mkdir(mode=0o700, exist_ok=True)
    _ = initialize_schedule_delivery_fence(root)
    _write_config(root, registry, _identity(registry_path))


def _write_config(
    root: Path, registry: CustomerRegistry, identity: WeeklyOperationsRegistryIdentity,
) -> None:
    weekly: dict[str, JsonValue] = {
        "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": {
        "profile_root": str(root), "registry_path": "registry.json",
        "weekly_operations_authority_path": "weekly-authority",
        "operator_review": {"user_id": "operator", "chat_id": "9001", "topic_id": 59},
        "weekly_operations": weekly,
    }}
    config = parse_weekly_operations_config(base)
    receipt: dict[str, JsonValue] = {
        "schema": "nutricoach-weekly-operations-authority-v2",
        "candidate_digest": CANDIDATE, "config_digest": config.digest,
        "enabled_customer_keys": [CUSTOMER],
        "owner": {"user_id": "coach", "chat_id": "owner-dm", "version": 7},
        "consent_digest": weekly_reminder_consent_digest(registry.customers[0]),
        "registry_identity": _identity_document(identity),
        "issued_at": "2026-08-16T00:00:00+09:00", "expires_at": "2026-08-26T00:00:00+09:00",
        "feature_epoch": "weekly-operations-v1",
    }
    nutrition = base["nutrition_coaching"]
    assert isinstance(nutrition, dict)
    nutrition["weekly_operations_authority"] = receipt
    nutrition["weekly_operations_authority_source"] = "operator"
    _ = (root / "platform-config.json").write_text(
        json.dumps(base, ensure_ascii=False, sort_keys=True), encoding="utf-8"
    )
    (root / "platform-config.json").chmod(0o600)


def load_platform_config(root: Path) -> PlatformConfig:
    from pydantic import TypeAdapter

    raw = TypeAdapter(dict[str, object]).validate_json(
        (root / "platform-config.json").read_text(encoding="utf-8")
    )
    return PlatformConfig(enabled=True, token="network-disabled", extra=raw)
