#!/usr/bin/env python3
"""Small native CLI for read-only fleet record access."""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="fleetctl",
        description="Read vehicle records from the local fleet registry.",
    )
    resources = parser.add_subparsers(dest="resource", required=True)
    vehicle = resources.add_parser("vehicle", help="access vehicle records")
    operations = vehicle.add_subparsers(dest="operation", required=True)

    get = operations.add_parser("get", help="retrieve one complete vehicle record")
    get.add_argument("--id", required=True, help="stable string vehicle ID")

    search = operations.add_parser("search", help="search vehicles by display name")
    search.add_argument("--name", required=True, help="display name to match")

    operations.add_parser("list", help="list all vehicle records")
    return parser


def registry_path() -> Path:
    configured = os.environ.get("FLEET_REGISTRY_PATH")
    if configured:
        return Path(configured)
    return Path(__file__).resolve().parent.parent / "data" / "vehicles.json"


def load_records() -> list[dict[str, Any]]:
    with registry_path().open(encoding="utf-8") as source:
        document = json.load(source)
    records = document.get("vehicles")
    if not isinstance(records, list):
        raise RuntimeError("fleet registry has no vehicle collection")
    return records


def append_audit(resource: str, operation: str, arguments: dict[str, str]) -> None:
    audit_path = os.environ.get("FLEET_AUDIT_PATH")
    if not audit_path:
        return
    event = {
        "arguments": arguments,
        "operation": operation,
        "resource": resource,
    }
    with Path(audit_path).open("a", encoding="utf-8") as audit:
        audit.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n")


def emit(value: Any) -> None:
    sys.stdout.write(json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n")


def main() -> int:
    args = build_parser().parse_args()
    records = load_records()

    if args.operation == "get":
        append_audit(args.resource, args.operation, {"id": args.id})
        record = next((item for item in records if item.get("id") == args.id), None)
        if record is None:
            print(f"fleetctl: vehicle not found: {args.id}", file=sys.stderr)
            return 4
        emit(record)
        return 0

    if args.operation == "search":
        append_audit(args.resource, args.operation, {"name": args.name})
        emit([item for item in records if item.get("name") == args.name])
        return 0

    append_audit(args.resource, args.operation, {})
    emit(records)
    return 0


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