#!/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
# ──────────────────

"""One-shot observer for actual production fsync and provider boundaries."""

from __future__ import annotations

import inspect
import json
import os
from contextlib import ExitStack
from dataclasses import asdict, dataclass
from pathlib import Path
from types import TracebackType
from typing import Final, Protocol, final
from unittest.mock import patch

from pydantic import TypeAdapter

_REAL_FSYNC: Final = os.fsync
_active: BoundaryObserver | None = None


class HasFileno(Protocol):
    def fileno(self) -> int: ...


@dataclass(frozen=True, slots=True)
class BoundaryEvent:
    step_id: str
    boundary: str


@final
class BoundaryObserver:
    """Mutable process-local observer installed only by the Todo10 child harness."""

    def __init__(self, root: Path, step_id: str, failpoint: str | None) -> None:
        self._path: Path = root / "boundary-events" / f"{step_id}-{os.getpid()}.jsonl"
        self._step_id: str = step_id
        self._failpoint: str | None = failpoint
        self._occurrences: dict[str, int] = {}
        self._patches = ExitStack()

    def __enter__(self) -> BoundaryObserver:
        global _active
        self._path.parent.mkdir(parents=True, exist_ok=True)
        _active = self
        _ = self._patches.enter_context(patch.object(os, "fsync", new=_observed_fsync))
        return self

    def __exit__(
        self, _kind: type[BaseException] | None, _error: BaseException | None,
        _traceback: TracebackType | None,
    ) -> bool:
        global _active
        self._patches.close()
        _active = None
        return False

    def observe(self, boundary: str) -> None:
        event = BoundaryEvent(self._step_id, boundary)
        descriptor = os.open(
            self._path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_CLOEXEC, 0o600
        )
        try:
            _ = os.write(
                descriptor,
                (json.dumps(asdict(event), sort_keys=True) + "\n").encode(),
            )
        finally:
            os.close(descriptor)
        occurrence = self._occurrences.get(boundary, 0) + 1
        self._occurrences[boundary] = occurrence
        if self._failpoint in {boundary, f"{boundary}#{occurrence}"}:
            os._exit(86)


def _observed_fsync(descriptor: int | HasFileno) -> None:
    fd = descriptor if isinstance(descriptor, int) else descriptor.fileno()
    _REAL_FSYNC(fd)
    active = _active
    if active is None:
        return
    caller = inspect.currentframe()
    parent = None if caller is None else caller.f_back
    if parent is None:
        return
    path = Path(parent.f_code.co_filename)
    active.observe(f"append_fsync:{path.name}:{parent.f_lineno}")


def observe_provider(operation: str) -> None:
    active = _active
    if active is not None:
        active.observe(f"provider:{operation}")


def read_boundary_events(root: Path) -> tuple[BoundaryEvent, ...]:
    events: list[BoundaryEvent] = []
    for path in sorted((root / "boundary-events").glob("*.jsonl")):
        for line in path.read_text(encoding="utf-8").splitlines():
            events.append(TypeAdapter(BoundaryEvent).validate_json(line))
    return tuple(events)
