#!/usr/bin/env python3
"""Executable fleet-record interface for a Pi dependency-planning task."""

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 / ".fleet"
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.45


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


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


def load_audit() -> 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
            value = json.loads(line)
            if not isinstance(value, dict):
                raise FleetError(f"invalid operation history at line {line_number}")
            events.append(value)
    return events


def atomic_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 record_digest(record: dict[str, Any]) -> str:
    return hashlib.sha256(canonical(record)).hexdigest()


def append_audit_locked(event: dict[str, Any]) -> None:
    sealed = dict(event)
    sealed["sequence"] = len(load_audit()) + 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_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 active(record: dict[str, Any]) -> bool:
    return record.get("archived") is False and record.get("cancelled") is False


def search_records(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    time.sleep(READ_DELAY_SECONDS)
    _, records = load_records()
    matches = [
        {
            "id": record["id"],
            "location": record["location"],
            "name": record["name"],
        }
        for record in records
        if active(record)
        and record.get("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 completed_search_ids() -> set[str]:
    events = load_audit()
    if len(events) != 2 or any(
        event.get("operation") != "search" or event.get("outcome") != "ok"
        for event in events
    ):
        raise FleetError("get requires exactly two completed searches")
    return {
        result_id
        for event in events
        for result_id in event.get("result_ids", [])
        if isinstance(result_id, str) and result_id
    }


def get_record(arguments: argparse.Namespace) -> int:
    started = time.monotonic_ns()
    try:
        returned_ids = completed_search_ids()
        if arguments.id not in returned_ids:
            raise FleetError("record ID was not returned by the completed searches")
    except FleetError as error:
        finished = time.monotonic_ns()
        append_audit(
            {
                "finished_ns": finished,
                "operation": "get",
                "outcome": "dependency-error",
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
        print(f"fleetctl: {error}", file=sys.stderr)
        return 4

    time.sleep(READ_DELAY_SECONDS)
    _, records = load_records()
    record = next(
        (record for record in records if active(record) and 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)
        print(f"fleetctl: record not found: {arguments.id}", file=sys.stderr)
        return 3
    event.update(
        {
            "date": record.get("date"),
            "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()
    with LOCK_PATH.open("a+", encoding="utf-8") as lock_stream:
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX)
        document, records = load_records()
        record = next((record for record in records if record.get("id") == arguments.id), None)
        before = record.get("status") if record is not None else None
        if record is not None:
            record["status"] = arguments.status
            atomic_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_locked(
            {
                "after_status": arguments.status,
                "before_status": before,
                "finished_ns": finished,
                "operation": "update",
                "outcome": "ok" if record is not None else "not-found",
                "record_id": arguments.id,
                "started_ns": started,
                "updated": record is not None,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit({"record_id": arguments.id, "updated": record is not None})
    return 0 if record is not None else 3


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, records = load_records()
        record = next((record for record in records if record.get("id") == arguments.id), None)
        if record is not None:
            record["cancelled"] = True
            atomic_write(RECORDS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_locked(
            {
                "cancelled": record is not None,
                "finished_ns": finished,
                "operation": "cancel",
                "outcome": "ok" if record is not None else "not-found",
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit({"cancelled": record is not None, "record_id": arguments.id})
    return 0 if record is not None else 3


def notify_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(NOTIFICATIONS_PATH)
        notifications = document.get("notifications")
        if document.get("version") != 1 or not isinstance(notifications, list):
            raise FleetError("invalid notification store")
        notifications.append(
            {
                "message": arguments.message,
                "ordinal": len(notifications) + 1,
                "record_id": arguments.id,
            }
        )
        atomic_write(NOTIFICATIONS_PATH, document)
        finished = time.monotonic_ns()
        append_audit_locked(
            {
                "finished_ns": finished,
                "operation": "notify",
                "outcome": "ok",
                "record_id": arguments.id,
                "started_ns": started,
            }
        )
        fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    emit({"notified": True, "record_id": arguments.id})
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="fleetctl",
        description="Search, retrieve, update, cancel, and notify fleet records.",
    )
    commands = parser.add_subparsers(dest="command", required=True)

    search_parser = commands.add_parser(
        "search", help="search active records by exact vehicle name and location"
    )
    search_parser.add_argument("--name", required=True)
    search_parser.add_argument("--location", required=True)
    search_parser.set_defaults(handler=search_records)

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

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

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

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


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


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