"""First-run acceptance gate (hard constraint #5) — the CLI counterpart to
`POST /v1/tos/accept` in the SaaS API. Recorded locally, not phoned home
(hard constraint #4: self-hosted is offline by default).
"""

import json
from datetime import UTC, datetime
from pathlib import Path

TOS_VERSION = "2026-07-23"


def _tos_state_path(home: Path | None = None) -> Path:
    base = home or Path.home()
    return base / ".abrade" / "tos_accepted.json"


def is_accepted(home: Path | None = None) -> bool:
    path = _tos_state_path(home)
    if not path.exists():
        return False
    try:
        data = json.loads(path.read_text())
    except (json.JSONDecodeError, OSError):
        return False
    return data.get("tos_version") == TOS_VERSION


def record_acceptance(accepted_by: str, *, home: Path | None = None) -> None:
    path = _tos_state_path(home)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(
            {
                "tos_version": TOS_VERSION,
                "accepted_by": accepted_by,
                "accepted_at": datetime.now(UTC).isoformat(),
            },
            indent=2,
        )
    )


TOS_PROMPT = (
    "By continuing, you confirm that you own the agent you are about to "
    "test, or are otherwise explicitly authorized to test it. Abrade fires "
    "adversarial telemetry at whatever agent-under-test you configure — "
    "only ever run this against systems you control."
)
