#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

from gateway.platforms.nutrition_service_state import (  # noqa: E402
    CustomerServiceStateStore,
)


def _profile_root(value: str) -> Path:
    candidate = Path(value).expanduser()
    if candidate.is_symlink():
        raise argparse.ArgumentTypeError("profile root symlinks are not allowed")
    try:
        resolved = candidate.resolve(strict=True)
    except OSError as exc:
        raise argparse.ArgumentTypeError("profile root is unavailable") from exc
    if not resolved.is_dir():
        raise argparse.ArgumentTypeError("profile root must be a directory")
    return resolved


def _initialize(profile_root: Path) -> dict[str, object]:
    state_path = (
        profile_root
        / "data"
        / "owner-actions"
        / "customer-service-state.json"
    )
    current = profile_root
    for part in state_path.relative_to(profile_root).parts[:-1]:
        current /= part
        if current.exists() and current.is_symlink():
            raise ValueError("service state path symlinks are not allowed")
    store = CustomerServiceStateStore(state_path)
    store.ensure()
    payload = json.loads(state_path.read_text(encoding="utf-8"))
    states = payload.get("states")
    digest = payload.get("payload_digest")
    if not isinstance(states, dict) or not isinstance(digest, str):
        raise ValueError("service state initializer produced invalid output")
    return {
        "schema": payload.get("schema"),
        "count": len(states),
        "digest": digest,
    }


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    commands = parser.add_subparsers(dest="command", required=True)
    initialize = commands.add_parser("init")
    initialize.add_argument("--profile-root", required=True, type=_profile_root)
    return parser


def main() -> int:
    args = _parser().parse_args()
    if args.command != "init":
        raise RuntimeError("unsupported service-state command")
    result = _initialize(args.profile_root)
    print(json.dumps(result, ensure_ascii=False, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
