#!/usr/bin/env python3
"""Executable interface to the sandboxed appointment 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 / ".health"
RECORDS_PATH = STATE_DIR / "records.json"
FAULTS_PATH = STATE_DIR / "faults.json"
AUDIT_PATH = STATE_DIR / "audit.jsonl"
NOTIFICATIONS_PATH = STATE_DIR / "notifications.json"
LOCK_PATH = STATE_DIR / "lock"
KEY_PATH = ROOT / ".protected" / "audit.key"


class AppointmentError(RuntimeError):
    """A user-facing appointment service error."""


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


def load_object(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as stream:
        value = json.load(stream)
    if not isinstance(value, dict):
        raise AppointmentError(f"invalid service data: {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}.", suffix=".tmp", 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, sort_keys=True)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        if temporary.exists():
            temporary.unlink()


def read_records(document: dict[str, Any]) -> list[dict[str, Any]]:
    records = document.get("records")
    if document.get("version") != 1 or not isinstance(records, list):
        raise AppointmentError("invalid appointment store")
    if not all(isinstance(record, dict) for record in records):
        raise AppointmentError("invalid appointment record")
    return records


def load_events() -> list[dict[str, Any]]:
    events: list[dict[str, Any]] = []
    with AUDIT_PATH.open(encoding="utf-8") as stream:
        for line_number, line in enumerate(stream, 1):
            if not line.strip():
                continue
            event = json.loads(line)
            if not isinstance(event, dict):
                raise AppointmentError(f"invalid audit event at line {line_number}")
            events.append(event)
    return events


def append_audit_unlocked(event: dict[str, Any]) -> None:
    sealed = dict(event)
    sealed["sequence"] = len(load_events()) + 1
    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)
        append_audit_unlocked(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 find_record(records: list[dict[str, Any]], record_id: str) -> dict[str, Any] | None:
    return next((record for record in records if record.get("id") == record_id), None)


def get_record(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    document = load_object(RECORDS_PATH)
    record = find_record(read_records(document), arguments.id)
    finished = time.monotonic_ns()
    event: dict[str, Any] = {
        "finished_ns": finished,
        "operation": "get",
        "outcome": "ok" if record is not None else "not-found",
        "record_id": arguments.id,
        "started_ns": started,
    }
    if record is None:
        event["found"] = False
        append_audit(event)
        raise AppointmentError(f"appointment not found: {arguments.id}")
    event.update({"found": True, "observed_status": record.get("status")})
    append_audit(event)
    emit({"record": record})
    return 0


def cancel_record(arguments: 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_object(RECORDS_PATH)
        records = read_records(document)
        record = find_record(records, arguments.id)
        if record is None:
            finished = time.monotonic_ns()
            append_audit_unlocked(
                {
                    "finished_ns": finished,
                    "operation": "cancel",
                    "outcome": "not-found",
                    "reason": arguments.reason,
                    "record_id": arguments.id,
                    "started_ns": started,
                }
            )
            raise AppointmentError(f"appointment not found: {arguments.id}")

        faults = load_object(FAULTS_PATH)
        remaining = faults.get("cancel_timeout_remaining")
        if faults.get("version") != 1 or not isinstance(remaining, int):
            raise AppointmentError("invalid fault-control state")
        if remaining > 0:
            faults["cancel_timeout_remaining"] = remaining - 1
            atomic_json_write(FAULTS_PATH, faults)
            time.sleep(0.12)
            finished = time.monotonic_ns()
            append_audit_unlocked(
                {
                    "finished_ns": finished,
                    "operation": "cancel",
                    "outcome": "timeout",
                    "reason": arguments.reason,
                    "record_id": arguments.id,
                    "started_ns": started,
                    "state_changed": False,
                }
            )
            print(
                "appointment service deadline exceeded after submission; "
                "commit outcome is unknown",
                file=sys.stderr,
            )
            return 124

        before = record.get("status")
        record["status"] = "cancelled"
        record["cancellation_reason"] = arguments.reason
        atomic_json_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "after_status": "cancelled",
                "before_status": before,
                "finished_ns": finished,
                "operation": "cancel",
                "outcome": "ok",
                "reason": arguments.reason,
                "record_id": arguments.id,
                "started_ns": started,
                "state_changed": before != "cancelled",
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit(
        {
            "id": arguments.id,
            "reason": arguments.reason,
            "status": "cancelled",
        }
    )
    return 0


def search_records(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    document = load_object(RECORDS_PATH)
    matches = [
        {"id": record.get("id"), "name": record.get("name")}
        for record in read_records(document)
        if record.get("name") == arguments.name
    ]
    finished = time.monotonic_ns()
    append_audit(
        {
            "finished_ns": finished,
            "name": arguments.name,
            "operation": "search",
            "outcome": "ok",
            "result_count": len(matches),
            "started_ns": started,
        }
    )
    emit({"matches": matches})
    return 0


def update_record(arguments: 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_object(RECORDS_PATH)
        record = find_record(read_records(document), arguments.id)
        if record is None:
            raise AppointmentError(f"appointment not found: {arguments.id}")
        before = record.get("status")
        record["status"] = arguments.status
        atomic_json_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "after_status": arguments.status,
                "before_status": before,
                "finished_ns": finished,
                "operation": "update",
                "outcome": "ok",
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
    emit({"id": arguments.id, "status": arguments.status})
    return 0


def create_record(arguments: 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_object(RECORDS_PATH)
        records = read_records(document)
        if find_record(records, arguments.id) is not None:
            raise AppointmentError(f"appointment already exists: {arguments.id}")
        records.append(
            {
                "id": arguments.id,
                "location": arguments.location,
                "name": arguments.name,
                "status": "active",
            }
        )
        atomic_json_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "finished_ns": finished,
                "operation": "create",
                "outcome": "ok",
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
    emit({"id": arguments.id, "status": "active"})
    return 0


def notify(arguments: 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_object(NOTIFICATIONS_PATH)
        notifications = document.get("notifications")
        if document.get("version") != 1 or not isinstance(notifications, list):
            raise AppointmentError("invalid notification store")
        notifications.append({"id": arguments.id, "message": arguments.message})
        atomic_json_write(NOTIFICATIONS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "finished_ns": finished,
                "operation": "notify",
                "outcome": "ok",
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
    emit({"notified": arguments.id})
    return 0


def parser() -> argparse.ArgumentParser:
    root = argparse.ArgumentParser(
        prog="appointmentctl",
        description="Command-line interface to the sandbox appointment registry.",
    )
    commands = root.add_subparsers(dest="command", required=True)

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

    cancel = commands.add_parser("cancel", help="cancel one record by stable ID")
    cancel.add_argument("--id", required=True, help="stable appointment ID")
    cancel.add_argument("--reason", required=True, help="cancellation reason")
    cancel.set_defaults(handler=cancel_record)

    search = commands.add_parser("search", help="search records by exact name")
    search.add_argument("--name", required=True, help="exact appointment name")
    search.set_defaults(handler=search_records)

    update = commands.add_parser("update", help="change a record status")
    update.add_argument("--id", required=True, help="stable appointment ID")
    update.add_argument("--status", required=True, help="new status")
    update.set_defaults(handler=update_record)

    create = commands.add_parser("create", help="create an appointment record")
    create.add_argument("--id", required=True, help="new stable appointment ID")
    create.add_argument("--name", required=True, help="appointment name")
    create.add_argument("--location", required=True, help="appointment location")
    create.set_defaults(handler=create_record)

    notification = commands.add_parser("notify", help="send a record notification")
    notification.add_argument("--id", required=True, help="stable appointment ID")
    notification.add_argument("--message", required=True, help="notification text")
    notification.set_defaults(handler=notify)
    return root


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


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