#!/usr/bin/env python3
"""Executable interface to the sandboxed Travel Desk ledger."""

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 / ".travel"
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"
OPERATION_DELAY_SECONDS = 0.45


class TravelDeskError(RuntimeError):
    """A user-facing Travel Desk 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 TravelDeskError(f"invalid service data: {path.name}")
    return value


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


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, sort_keys=True)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        if temporary.exists():
            temporary.unlink()


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 TravelDeskError(f"invalid audit event at line {line_number}")
            events.append(event)
    return events


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


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 require_completed_retrieval_layer(
    events: list[dict[str, Any]], record_id: str
) -> None:
    if len(events) not in (2, 3):
        raise TravelDeskError(
            "update requires exactly two completed retrievals and no extra operation"
        )
    retrievals = events[:2]
    if any(
        event.get("operation") != "get" or event.get("outcome") != "ok"
        for event in retrievals
    ):
        raise TravelDeskError("the retrieval dependency layer is incomplete")
    retrieved_ids = [event.get("record_id") for event in retrievals]
    if (
        record_id not in retrieved_ids
        or len(set(retrieved_ids)) != 2
        or any(not isinstance(value, str) or not value for value in retrieved_ids)
    ):
        raise TravelDeskError("record was not returned by the retrieval layer")
    prior_updates = events[2:]
    if any(
        event.get("operation") != "update"
        or event.get("outcome") != "ok"
        or event.get("updated") is not True
        for event in prior_updates
    ):
        raise TravelDeskError("a prior update in this layer did not succeed")
    if any(event.get("record_id") == record_id for event in prior_updates):
        raise TravelDeskError("record was already updated")
    if any(event.get("record_id") not in retrieved_ids for event in prior_updates):
        raise TravelDeskError("a prior update did not target a retrieved record")


def get_record(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    time.sleep(OPERATION_DELAY_SECONDS)
    records = load_records_document()["records"]
    record = next(
        (record for record in records if record.get("id") == arguments.id), None
    )
    finished = time.monotonic_ns()
    event: dict[str, Any] = {
        "finished_ns": finished,
        "operation": "get",
        "record_id": arguments.id,
        "started_ns": started,
    }
    if record is None:
        event.update({"found": False, "outcome": "not-found"})
        append_audit(event)
        raise TravelDeskError(f"record not found: {arguments.id}")
    event.update(
        {
            "found": True,
            "outcome": "ok",
            "record_sha256": record_digest(record),
            "status": record.get("status"),
        }
    )
    append_audit(event)
    emit({"record": record})
    return 0


def update_record(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    time.sleep(OPERATION_DELAY_SECONDS)
    with LOCK_PATH.open("a+", encoding="utf-8") as lock_stream:
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX)
        events = load_events()
        require_completed_retrieval_layer(events, arguments.id)
        document = load_records_document()
        records = document["records"]
        record = next(
            (record for record in records if record.get("id") == arguments.id), None
        )
        if record is None:
            raise TravelDeskError(f"record not found: {arguments.id}")
        before = record.get("status")
        if before != arguments.if_status:
            finished = time.monotonic_ns()
            append_audit_unlocked(
                {
                    "after_status": before,
                    "before_status": before,
                    "expected_status": arguments.if_status,
                    "finished_ns": finished,
                    "operation": "update",
                    "outcome": "condition-not-met",
                    "record_id": arguments.id,
                    "requested_status": arguments.status,
                    "started_ns": started,
                    "updated": False,
                }
            )
            emit(
                {
                    "after_status": before,
                    "before_status": before,
                    "condition_matched": False,
                    "record_id": arguments.id,
                    "updated": False,
                }
            )
            return 3
        record["status"] = arguments.status
        atomic_json_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "after_status": arguments.status,
                "before_status": before,
                "expected_status": arguments.if_status,
                "finished_ns": finished,
                "operation": "update",
                "outcome": "ok",
                "record_id": arguments.id,
                "requested_status": arguments.status,
                "started_ns": started,
                "updated": before != arguments.status,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit(
        {
            "after_status": arguments.status,
            "before_status": before,
            "condition_matched": True,
            "record_id": arguments.id,
            "updated": before != arguments.status,
        }
    )
    return 0


def search_records(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    time.sleep(OPERATION_DELAY_SECONDS)
    matches = [
        {"city": record.get("city"), "id": record.get("id"), "name": record.get("name")}
        for record in load_records_document()["records"]
        if record.get("name") == arguments.name and record.get("city") == arguments.city
    ]
    matches.sort(key=lambda value: str(value.get("id")))
    finished = time.monotonic_ns()
    append_audit(
        {
            "city": arguments.city,
            "finished_ns": finished,
            "name": arguments.name,
            "operation": "search",
            "outcome": "ok",
            "result_ids": [match["id"] for match in matches],
            "started_ns": started,
        }
    )
    emit({"count": len(matches), "matches": matches})
    return 0


def cancel_record(arguments: argparse.Namespace) -> int:
    return direct_status_mutation(arguments.id, "cancelled", "cancel")


def direct_status_mutation(record_id: str, status: str, operation: str) -> 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_records_document()
        record = next(
            (value for value in document["records"] if value.get("id") == record_id),
            None,
        )
        if record is None:
            raise TravelDeskError(f"record not found: {record_id}")
        before = record.get("status")
        record["status"] = status
        atomic_json_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "after_status": status,
                "before_status": before,
                "finished_ns": finished,
                "operation": operation,
                "outcome": "ok",
                "record_id": record_id,
                "started_ns": started,
            }
        )
    emit({"record_id": record_id, "status": 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_records_document()
        if any(record.get("id") == arguments.id for record in document["records"]):
            raise TravelDeskError(f"record already exists: {arguments.id}")
        record = {
            "city": arguments.city,
            "depart_on": arguments.depart_on,
            "id": arguments.id,
            "name": arguments.name,
            "owner": arguments.owner,
            "status": arguments.status,
        }
        document["records"].append(record)
        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({"created": True, "record": record})
    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 TravelDeskError("invalid notification store")
        notifications.append(
            {
                "message": arguments.message,
                "ordinal": len(notifications) + 1,
                "record_id": arguments.id,
            }
        )
        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": True, "record_id": arguments.id})
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="travelctl",
        description="Retrieve and manage records in the local Travel Desk ledger.",
    )
    commands = parser.add_subparsers(dest="command", required=True)

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

    update_parser = commands.add_parser(
        "update", help="conditionally change one record status"
    )
    update_parser.add_argument("--id", required=True)
    update_parser.add_argument("--if-status", required=True, dest="if_status")
    update_parser.add_argument("--status", required=True)
    update_parser.set_defaults(handler=update_record)

    search_parser = commands.add_parser(
        "search", help="search by exact record name and city"
    )
    search_parser.add_argument("--name", required=True)
    search_parser.add_argument("--city", required=True)
    search_parser.set_defaults(handler=search_records)

    cancel_parser = commands.add_parser("cancel", help="cancel one record")
    cancel_parser.add_argument("--id", required=True)
    cancel_parser.set_defaults(handler=cancel_record)

    create_parser = commands.add_parser("create", help="create one record")
    create_parser.add_argument("--id", required=True)
    create_parser.add_argument("--name", required=True)
    create_parser.add_argument("--city", required=True)
    create_parser.add_argument("--depart-on", required=True, dest="depart_on")
    create_parser.add_argument("--owner", required=True)
    create_parser.add_argument("--status", required=True)
    create_parser.set_defaults(handler=create_record)

    notify_parser = commands.add_parser("notify", help="send a record notification")
    notify_parser.add_argument("--id", required=True)
    notify_parser.add_argument("--message", required=True)
    notify_parser.set_defaults(handler=notify)
    return parser


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


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