from __future__ import annotations

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


ROOT = Path(__file__).resolve().parent
SCRIPT = ROOT / "branding_staff_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-staff-membership-v1"
    archive = profile / "data/onboarding-archive/nutricoach-staff-membership"
    receipt = tmp_path / "staff-reset-receipt.json"
    source.mkdir(parents=True, mode=0o700)
    (profile / "customers").mkdir(mode=0o700)
    _write_json(
        profile / "customers/registry.json",
        {
            "customers": [
                {
                    "enabled": False,
                    "ai_processing_consent": {"granted": False},
                }
            ]
        },
    )
    events = source / "events.jsonl"
    events.write_text('{"event":"subscription_armed"}\n')
    events.chmod(0o600)
    (source / "events.jsonl.lock").write_text("")
    (source / "events.jsonl.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-staff-reset-permission-v1",
            "profile": str(profile),
            "source_root": str(source),
            "archive_root": str(archive),
            "receipt_path": str(receipt),
            "events_sha256": _sha(events),
            "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_staff_membership_authority(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 (archive / "events.jsonl").is_file()
    receipt = json.loads((tmp_path / "staff-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

    assert _run(permission, env).returncode == 2


def test_reset_refuses_active_gateway(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()
