#!/usr/bin/env python3
"""Executable interface for the sandboxed hospitality reservation registry."""

from __future__ import annotations

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


ROOT = Path(__file__).resolve().parent
STATE_DIR = ROOT / ".reservations"
RECORDS_PATH = STATE_DIR / "records.json"
AUDIT_PATH = STATE_DIR / "audit.jsonl"
NOTIFICATIONS_PATH = STATE_DIR / "notifications.json"
LOCK_PATH = STATE_DIR / "lock"
KEY_PATH = ROOT / ".harness" / "audit.key"
READ_DELAY_SECONDS = 0.55


def canonical(value: Any) -> bytes:
    return json.dumps(
        value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
    ).encode("utf-8")


def load_document(path: Path, collection: str) -> dict[str, Any]:
    with path.open(encoding="utf-8") as stream:
        value = json.load(stream)
    if (
        not isinstance(value, dict)
        or value.get("version") != 1
        or not isinstance(value.get(collection), list)
    ):
        raise RuntimeError(f"invalid registry document: {path.name}")
    return value


def atomic_json_write(path: Path, value: dict[str, Any]) -> None:
    descriptor, temporary_name = tempfile.mkstemp(
        dir=path.parent, prefix=f".{path.name}.", text=True
    )
    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, path)
    finally:
        if temporary.exists():
            temporary.unlink()


def read_records() -> list[dict[str, Any]]:
    document = load_document(RECORDS_PATH, "records")
    records = document["records"]
    if not all(isinstance(record, dict) for record in records):
        raise RuntimeError("invalid record entry")
    return records


def record_digest(record: dict[str, Any]) -> str:
    return hashlib.sha256(canonical(record)).hexdigest()


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


def append_audit(event: dict[str, Any]) -> None:
    with LOCK_PATH.open("a+", encoding="utf-8") as lock_stream:
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX)
        write_audit_locked(event)
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)


def emit(value: dict[str, Any]) -> None:
    json.dump(value, sys.stdout, ensure_ascii=False, sort_keys=True)
    sys.stdout.write("\n")


def search(args: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    time.sleep(READ_DELAY_SECONDS)
    matches = [
        {
            "id": record["id"],
            "name": record["name"],
            "location": record["location"],
        }
        for record in read_records()
        if record.get("name") == args.name and record.get("location") == args.location
    ]
    matches.sort(key=lambda record: record["id"])
    finished = time.monotonic_ns()
    append_audit(
        {
            "operation": "search",
            "name": args.name,
            "location": args.location,
            "started_ns": started,
            "finished_ns": finished,
            "outcome": "ok",
            "result_ids": [record["id"] for record in matches],
        }
    )
    emit({"count": len(matches), "matches": matches})
    return 0


def get_record(args: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    time.sleep(READ_DELAY_SECONDS)
    record = next(
        (record for record in read_records() if record.get("id") == args.id), None
    )
    finished = time.monotonic_ns()
    event: dict[str, Any] = {
        "operation": "get",
        "record_id": args.id,
        "started_ns": started,
        "finished_ns": finished,
    }
    if record is None:
        event.update({"outcome": "not-found", "found": False})
        append_audit(event)
        print(f"reservation not found: {args.id}", file=sys.stderr)
        return 3
    event.update(
        {
            "outcome": "ok",
            "found": True,
            "record_sha256": record_digest(record),
            "status": record.get("status"),
        }
    )
    append_audit(event)
    emit({"record": record})
    return 0


def cancel_record(args: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    with LOCK_PATH.open("a+", encoding="utf-8") as lock_stream:
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX)
        document = load_document(RECORDS_PATH, "records")
        record = next(
            (item for item in document["records"] if item.get("id") == args.id), None
        )
        before = record.get("status") if record is not None else None
        if record is None:
            outcome = "not-found"
            cancelled = 0
        elif before != "held":
            outcome = "not-held"
            cancelled = 0
        else:
            record["status"] = "cancelled"
            record["cancellation_reason"] = args.reason
            atomic_json_write(RECORDS_PATH, document)
            outcome = "ok"
            cancelled = 1
        finished = time.monotonic_ns()
        write_audit_locked(
            {
                "operation": "cancel",
                "record_id": args.id,
                "reason": args.reason,
                "before_status": before,
                "after_status": record.get("status") if record is not None else None,
                "cancelled": cancelled,
                "started_ns": started,
                "finished_ns": finished,
                "outcome": outcome,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)

    if cancelled != 1:
        print(f"cancellation not performed: {outcome}", file=sys.stderr)
        return 4 if outcome == "not-held" else 3
    emit(
        {
            "cancelled": cancelled,
            "before_status": before,
            "record": record,
        }
    )
    return 0


def notify(args: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    with LOCK_PATH.open("a+", encoding="utf-8") as lock_stream:
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX)
        records = load_document(RECORDS_PATH, "records")["records"]
        record = next((item for item in records if item.get("id") == args.id), None)
        document = load_document(NOTIFICATIONS_PATH, "notifications")
        if record is None:
            outcome = "not-found"
            delivered = 0
            notification = None
        elif record.get("status") != "cancelled" or not record.get(
            "cancellation_reason"
        ):
            outcome = "not-cancelled"
            delivered = 0
            notification = None
        else:
            message = (
                f"{record['name']} in {record['location']} was cancelled. "
                f"Reason: {record['cancellation_reason']}."
            )
            notification = {
                "ordinal": len(document["notifications"]) + 1,
                "recipient": args.recipient,
                "record_id": args.id,
                "message": message,
            }
            document["notifications"].append(notification)
            atomic_json_write(NOTIFICATIONS_PATH, document)
            outcome = "ok"
            delivered = 1
        finished = time.monotonic_ns()
        write_audit_locked(
            {
                "operation": "notify",
                "record_id": args.id,
                "recipient": args.recipient,
                "message_sha256": (
                    hashlib.sha256(notification["message"].encode("utf-8")).hexdigest()
                    if notification is not None
                    else None
                ),
                "delivered": delivered,
                "started_ns": started,
                "finished_ns": finished,
                "outcome": outcome,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)

    if delivered != 1:
        print(f"notification not delivered: {outcome}", file=sys.stderr)
        return 4 if outcome == "not-cancelled" else 3
    emit({"delivered": delivered, "notification": notification})
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="reservation-registry",
        description="Search, retrieve, cancel, and notify hospitality reservations.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    search_parser = subparsers.add_parser(
        "search", help="search by an exact reservation name and location"
    )
    search_parser.add_argument("--name", required=True)
    search_parser.add_argument("--location", required=True)
    search_parser.set_defaults(handler=search)

    get_parser = subparsers.add_parser("get", help="retrieve one complete record by ID")
    get_parser.add_argument("--id", required=True)
    get_parser.set_defaults(handler=get_record)

    cancel_parser = subparsers.add_parser(
        "cancel", help="cancel one held reservation by ID with a reason"
    )
    cancel_parser.add_argument("--id", required=True)
    cancel_parser.add_argument("--reason", required=True)
    cancel_parser.set_defaults(handler=cancel_record)

    notify_parser = subparsers.add_parser(
        "notify", help="notify a recipient of one cancelled reservation's outcome"
    )
    notify_parser.add_argument("--id", required=True)
    notify_parser.add_argument("--recipient", required=True)
    notify_parser.set_defaults(handler=notify)
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()
    try:
        return int(args.handler(args))
    except (OSError, RuntimeError, json.JSONDecodeError) as error:
        print(f"registry error: {error}", file=sys.stderr)
        return 2


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