#!/usr/bin/env python3
"""Executable interface to the sandboxed shipment 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 / ".shipping"
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 / ".protected" / "audit.key"
READ_DELAY_SECONDS = 0.55
CANCELLATION_REASON = "Sender withdrew the shipment before dispatch"


class ShippingError(RuntimeError):
    """A user-facing shipping 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 ShippingError(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}.", 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() -> list[dict[str, Any]]:
    document = load_object(RECORDS_PATH)
    records = document.get("records")
    if document.get("version") != 1 or not isinstance(records, list):
        raise ShippingError("invalid shipment store")
    if not all(isinstance(record, dict) for record in records):
        raise ShippingError("invalid shipment 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 ShippingError(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_search_layer(record_id: str) -> None:
    events = load_events()
    if len(events) != 2 or [event.get("operation") for event in events] != [
        "search",
        "search",
    ]:
        raise ShippingError("get requires exactly two completed searches")
    if any(event.get("outcome") != "ok" for event in events):
        raise ShippingError("a search prerequisite did not succeed")
    if any(
        not isinstance(event.get("result_ids"), list)
        or len(event["result_ids"]) != 1
        for event in events
    ):
        raise ShippingError("every search must resolve to exactly one shipment")
    returned_ids = {event["result_ids"][0] for event in events}
    if record_id not in returned_ids:
        raise ShippingError("shipment ID was not returned by the completed searches")


def require_completed_get_layer(
    events: list[dict[str, Any]], record_id: str
) -> dict[str, Any]:
    if len(events) != 4:
        raise ShippingError("cancel requires two searches and two retrievals")
    if [event.get("operation") for event in events[:2]] != ["search", "search"]:
        raise ShippingError("search layer is incomplete")
    if [event.get("operation") for event in events[2:]] != ["get", "get"]:
        raise ShippingError("retrieval layer is incomplete")
    if any(event.get("outcome") != "ok" for event in events):
        raise ShippingError("a prerequisite operation did not succeed")
    if any(len(event.get("result_ids", [])) != 1 for event in events[:2]):
        raise ShippingError("a search was not uniquely resolved")
    retrieved = [
        event for event in events[2:] if event.get("record_id") == record_id
    ]
    if len(retrieved) != 1:
        raise ShippingError("shipment ID was not retrieved exactly once")
    return retrieved[0]


def require_successful_cancel(
    events: list[dict[str, Any]], record_id: str
) -> dict[str, Any]:
    if len(events) != 5:
        raise ShippingError("notice requires the completed cancellation path")
    cancellation = events[-1]
    if (
        cancellation.get("operation") != "cancel"
        or cancellation.get("outcome") != "ok"
        or cancellation.get("record_id") != record_id
        or cancellation.get("cancelled") is not True
    ):
        raise ShippingError("notice requires a successful cancellation")
    return cancellation


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


def get_shipment(arguments: argparse.Namespace) -> int:
    require_completed_search_layer(arguments.id)
    started = time.monotonic_ns()
    time.sleep(READ_DELAY_SECONDS)
    record = next(
        (record for record in read_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 ShippingError(f"shipment 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 cancel_shipment(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)
        events = load_events()
        retrieved = require_completed_get_layer(events, arguments.id)
        document = load_object(RECORDS_PATH)
        records = document.get("records")
        if not isinstance(records, list):
            raise ShippingError("invalid shipment store")
        record = next(
            (record for record in records if record.get("id") == arguments.id),
            None,
        )
        if record is None:
            raise ShippingError(f"shipment not found: {arguments.id}")
        before = record.get("status")
        if retrieved.get("status") != arguments.if_status:
            raise ShippingError("conditional status does not match retrieved shipment")
        if before != arguments.if_status:
            finished = time.monotonic_ns()
            append_audit_unlocked(
                {
                    "actual_status": before,
                    "cancelled": False,
                    "expected_status": arguments.if_status,
                    "finished_ns": finished,
                    "operation": "cancel",
                    "outcome": "guard-not-met",
                    "record_id": arguments.id,
                    "started_ns": started,
                }
            )
            print(
                f"shippingctl: cancellation skipped; status is {before!r}, not "
                f"{arguments.if_status!r}",
                file=sys.stderr,
            )
            return 3
        record["cancellation_reason"] = arguments.reason
        record["status"] = "cancelled"
        atomic_json_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "after_status": "cancelled",
                "before_status": before,
                "cancelled": True,
                "finished_ns": finished,
                "operation": "cancel",
                "outcome": "ok",
                "reason": arguments.reason,
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit(
        {
            "after_status": "cancelled",
            "before_status": before,
            "cancelled": True,
            "reason": arguments.reason,
            "record_id": arguments.id,
        }
    )
    return 0


def notify_shipping_desk(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)
        events = load_events()
        cancellation = require_successful_cancel(events, arguments.id)
        record = next(
            (record for record in read_records() if record.get("id") == arguments.id),
            None,
        )
        if record is None:
            raise ShippingError(f"shipment not found: {arguments.id}")
        if (
            record.get("status") != cancellation.get("after_status")
            or record.get("cancellation_reason") != cancellation.get("reason")
        ):
            raise ShippingError("shipment no longer matches the cancellation")
        subject = f"Shipment cancelled: {record.get('shipment_name')}"
        body = (
            f"{record.get('shipment_name')} was cancelled from "
            f"{cancellation.get('before_status')} with reason "
            f"\"{cancellation.get('reason')}\"."
        )
        document = load_object(NOTIFICATIONS_PATH)
        notifications = document.get("notifications")
        if not isinstance(notifications, list):
            raise ShippingError("invalid notification store")
        notification = {
            "body": body,
            "ordinal": len(notifications) + 1,
            "recipient": arguments.recipient,
            "record_id": arguments.id,
            "subject": subject,
        }
        notifications.append(notification)
        atomic_json_write(NOTIFICATIONS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_unlocked(
            {
                "finished_ns": finished,
                "notification_sha256": hashlib.sha256(
                    canonical(notification)
                ).hexdigest(),
                "operation": "notify",
                "outcome": "ok",
                "recipient": arguments.recipient,
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit(
        {
            "body": body,
            "delivered": True,
            "recipient": arguments.recipient,
            "record_id": arguments.id,
            "subject": subject,
        }
    )
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="shippingctl",
        description=(
            "Search, retrieve, conditionally cancel, and send outcome notices "
            "for local shipment records."
        ),
        epilog=(
            "Command forms:\n"
            "  shippingctl search --name NAME --location LOCATION\n"
            "  shippingctl get --id ID\n"
            "  shippingctl cancel --id ID --if-status STATUS --reason REASON\n"
            "  shippingctl notify --id ID --recipient RECIPIENT"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    commands = parser.add_subparsers(dest="command", required=True)

    search_parser = commands.add_parser(
        "search", help="search by exact shipment name and exact location"
    )
    search_parser.add_argument("--name", required=True)
    search_parser.add_argument("--location", required=True)
    search_parser.set_defaults(handler=search_shipments)

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

    cancel_parser = commands.add_parser(
        "cancel", help="conditionally cancel one retrieved shipment"
    )
    cancel_parser.add_argument("--id", required=True)
    cancel_parser.add_argument("--if-status", required=True)
    cancel_parser.add_argument(
        "--reason", required=True, choices=(CANCELLATION_REASON,)
    )
    cancel_parser.set_defaults(handler=cancel_shipment)

    notify_parser = commands.add_parser(
        "notify", help="send the outcome of the immediately preceding cancellation"
    )
    notify_parser.add_argument("--id", required=True)
    notify_parser.add_argument(
        "--recipient", required=True, choices=("shipping desk",)
    )
    notify_parser.set_defaults(handler=notify_shipping_desk)
    return parser


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


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