#!/usr/bin/env python3
"""Executable rollout interface for facilities-request capabilities."""

from __future__ import annotations

import fcntl
import hashlib
import hmac
import json
import os
from pathlib import Path
import sys
import tempfile
from typing import Any


ROOT = Path(__file__).resolve().parent
STATE = ROOT / ".facilities"
DEPLOYMENT = STATE / "deployment.json"
AUDIT = STATE / "audit.jsonl"
LOCK = STATE / "lock"
KEY = ROOT / ".harness" / "audit.key"


def canonical(value: dict[str, Any]) -> bytes:
    return json.dumps(
        value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
    ).encode()


def load() -> dict[str, Any]:
    with DEPLOYMENT.open(encoding="utf-8") as stream:
        value = json.load(stream)
    if not isinstance(value, dict):
        raise RuntimeError("invalid deployment state")
    return value


def save(value: dict[str, Any]) -> None:
    descriptor, temporary_name = tempfile.mkstemp(dir=DEPLOYMENT.parent)
    temporary = Path(temporary_name)
    try:
        with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
            json.dump(value, stream, ensure_ascii=False, indent=2)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, DEPLOYMENT)
    finally:
        temporary.unlink(missing_ok=True)


def append_locked(event: dict[str, Any]) -> None:
    with AUDIT.open(encoding="utf-8") as stream:
        sequence = sum(1 for line in stream if line.strip()) + 1
    sealed = dict(event, sequence=sequence)
    sealed["signature"] = hmac.new(
        KEY.read_bytes().strip(), canonical(sealed), hashlib.sha256
    ).hexdigest()
    with AUDIT.open("a", encoding="utf-8") as stream:
        stream.write(json.dumps(sealed, ensure_ascii=False, sort_keys=True) + "\n")
        stream.flush()
        os.fsync(stream.fileno())


def show_help() -> int:
    with LOCK.open("a+", encoding="utf-8") as lock:
        fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
        append_locked(
            {
                "operation": "admin-capabilities",
                "executable": "facilities-admin",
                "outcome": "ok",
                "actions": ["activate-cancellation"],
            }
        )
    print("Facilities capability rollout")
    print("Usage: ./facilities-admin <action>")
    print("Actions:")
    print("  activate-cancellation  enable the approved cancellation package")
    return 0


def activate() -> int:
    with LOCK.open("a+", encoding="utf-8") as lock:
        fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
        deployment = load()
        if (
            deployment.get("version") != 1
            or not isinstance(deployment.get("revision"), int)
        ):
            raise RuntimeError("invalid deployment state")
        before = deployment.get("cancellation_enabled") is True
        if before:
            outcome = "already-enabled"
        else:
            deployment["cancellation_enabled"] = True
            deployment["revision"] += 1
            save(deployment)
            outcome = "ok"
        append_locked(
            {
                "operation": "deployment",
                "executable": "facilities-admin",
                "outcome": outcome,
                "action": "activate-cancellation",
                "before_enabled": before,
                "after_enabled": deployment.get("cancellation_enabled") is True,
                "revision": deployment["revision"],
            }
        )
    if outcome != "ok":
        print("cancellation package is already enabled", file=sys.stderr)
        return 4
    print(
        json.dumps(
            {
                "activated": 1,
                "capability": "cancellation",
                "revision": deployment["revision"],
            },
            sort_keys=True,
        )
    )
    return 0


def main() -> int:
    try:
        if sys.argv[1:] in (["--help"], ["-h"]):
            return show_help()
        if sys.argv[1:] == ["activate-cancellation"]:
            return activate()
        print("use ./facilities-admin --help", file=sys.stderr)
        return 2
    except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as error:
        print(f"facilities-admin: {error}", file=sys.stderr)
        return 2


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