"""Small hand-off protocol between a Factory run and its launcher supervisor.

The Factory launcher owns crash notification because it remains alive when its
Python child is SIGKILLed or otherwise disappears.  The child only writes these
markers; it never uses them to notify the owner.
"""

from __future__ import annotations

import os
from pathlib import Path


def _status_path() -> Path | None:
    raw = os.environ.get("FACTORY_SUPERVISOR_STATUS_FILE", "").strip()
    return Path(raw) if raw else None


def _write(state: str, adw_id: str) -> None:
    """Atomically publish the run id and its terminal state, if supervised."""
    path = _status_path()
    if path is None:
        return
    try:
        temporary = path.with_suffix(".tmp")
        temporary.write_text(f"{state} {adw_id}\n", encoding="utf-8")
        temporary.replace(path)
    except OSError:
        # The trace remains authoritative; supervision observability must not
        # turn a usable Factory run into a failed one.
        pass


def started(adw_id: str) -> None:
    _write("started", adw_id)


def finished(adw_id: str) -> None:
    _write("finished", adw_id)
