from __future__ import annotations

import hashlib
import json
import os
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parent
SCRIPT = ROOT / "branding_invite_reset.py"
AUTHORIZATION = ROOT / "nutricoach-branding-authorization.json"
PYTHON = Path("/home/cube/projects/richard/hermes-agent/.venv/bin/python")


def _sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def _write_json(path: Path, value: dict[str, object]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    path.write_text(json.dumps(value, sort_keys=True, separators=(",", ":")))
    path.chmod(0o600)


def _fixture(
    tmp_path: Path,
    *,
    active: bool = False,
) -> tuple[Path, Path, Path, dict[str, str]]:
    profile = tmp_path / "profile"
    source = profile / "data/onboarding/telegram-customer-bootstrap-v1"
    archive = profile / "data/onboarding-archive/nutricoach-migration"
    receipt = tmp_path / "reset-receipt.json"
    source.mkdir(parents=True, mode=0o700)
    (profile / "customers").mkdir(mode=0o700)
    _write_json(
        profile / "customers/registry.json",
        {
            "customers": [
                {
                    "customer_key": "historical-synthetic",
                    "enabled": False,
                    "ai_processing_consent": {"granted": False},
                }
            ]
        },
    )
    _write_json(
        source / "ledger.json",
        {
            "sessions": [
                {
                    "session_id": "cb_old",
                    "sid_hash": "a" * 64,
                    "state": "PREPARED",
                    "generation": 1,
                    "bot_username": "dual_coach_pilot_test_bot",
                    "role_claims": [],
                    "customer_draft": {"customer_user_id": None},
                }
            ]
        },
    )
    (source / "ledger.lock").write_text("")
    (source / "ledger.lock").chmod(0o600)
    fake_bin = tmp_path / "bin"
    fake_bin.mkdir()
    systemctl = fake_bin / "systemctl"
    state = (
        "MainPID=123\\nActiveState=active\\nSubState=running\\n"
        if active
        else "MainPID=0\\nActiveState=inactive\\nSubState=dead\\n"
    )
    systemctl.write_text(f"#!/bin/sh\nprintf '{state}'\n")
    systemctl.chmod(0o700)
    permission = tmp_path / "permission.json"
    _write_json(
        permission,
        {
            "schema": "dualcoach-branding-invite-reset-permission-v1",
            "profile": str(profile),
            "source_root": str(source),
            "archive_root": str(archive),
            "receipt_path": str(receipt),
            "session_id": "cb_old",
            "sid_hash": "a" * 64,
            "ledger_sha256": _sha(source / "ledger.json"),
            "authorization_path": str(AUTHORIZATION),
            "authorization_sha256": _sha(AUTHORIZATION),
            "script_sha256": _sha(SCRIPT) if SCRIPT.exists() else "0" * 64,
        },
    )
    env = {
        **os.environ,
        "PATH": f"{fake_bin}:{os.environ['PATH']}",
        "PYTHONDONTWRITEBYTECODE": "1",
    }
    return permission, source, archive, env


def _run(permission: Path, env: dict[str, str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [str(PYTHON), "-B", str(SCRIPT), "--permission", str(permission)],
        check=False,
        capture_output=True,
        text=True,
        env=env,
    )


def test_reset_archives_only_unclaimed_old_bot_invite(tmp_path: Path) -> None:
    permission, source, archive, env = _fixture(tmp_path)

    result = _run(permission, env)

    assert result.returncode == 0, result.stderr
    assert not source.exists()
    assert json.loads((archive / "ledger.json").read_text())["sessions"][0][
        "bot_username"
    ] == "dual_coach_pilot_test_bot"
    receipt = json.loads((tmp_path / "reset-receipt.json").read_text())
    assert receipt["status"] == "PASS_ARCHIVED"


def test_reset_is_one_use(tmp_path: Path) -> None:
    permission, _, _, env = _fixture(tmp_path)
    assert _run(permission, env).returncode == 0

    repeated = _run(permission, env)

    assert repeated.returncode == 2


def test_reset_refuses_while_gateway_active(tmp_path: Path) -> None:
    permission, source, archive, env = _fixture(tmp_path, active=True)

    result = _run(permission, env)

    assert result.returncode == 2
    assert source.exists()
    assert not archive.exists()
