#!/usr/bin/env python3
"""Make Hermes' deferred TUI agent startup deadline operator-configurable."""

from __future__ import annotations

import argparse
from pathlib import Path


BEFORE = '''def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:
    ready = session.get("agent_ready")
    if ready is not None and not ready.wait(timeout=timeout):
        return _err(rid, 5032, "agent initialization timed out")
'''
AFTER = '''def _agent_init_timeout() -> float:
    """Return the bounded startup allowance for tool-heavy TUI sessions."""
    try:
        configured = float(
            os.environ.get("HERMES_TUI_AGENT_INIT_TIMEOUT_S", "180")
        )
    except (TypeError, ValueError):
        configured = 180.0
    return max(30.0, min(configured, 900.0))


def _wait_agent(
    session: dict, rid: str, timeout: float | None = None
) -> dict | None:
    ready = session.get("agent_ready")
    wait_timeout = _agent_init_timeout() if timeout is None else timeout
    if ready is not None and not ready.wait(timeout=wait_timeout):
        return _err(rid, 5032, "agent initialization timed out")
'''


def patch(source: Path, destination: Path) -> None:
    """Apply the narrow timeout override and fail on upstream drift."""
    content = source.read_text(encoding="utf-8")
    if BEFORE not in content:
        raise RuntimeError("Hermes TUI gateway patch context changed")
    destination.parent.mkdir(parents=True, exist_ok=True)
    destination.write_text(content.replace(BEFORE, AFTER, 1), encoding="utf-8")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("destination", type=Path)
    args = parser.parse_args()
    patch(args.source, args.destination)
    return 0


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