#!/usr/bin/env python3
"""Command-line client for the sandboxed appointment operations system."""

from __future__ import annotations

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


ROOT = Path(__file__).resolve().parent
SERVICE = ROOT / ".appointments" / "service.py"
COMMITTED_RESPONSE_DEADLINE_EXIT = 75


def call_service(request: dict[str, str]) -> dict[str, Any]:
    process = subprocess.Popen(
        [sys.executable, "-B", str(SERVICE)],
        cwd=ROOT,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    stdout, stderr = process.communicate(
        json.dumps(request, ensure_ascii=False, separators=(",", ":")) + "\n"
    )
    if process.returncode == COMMITTED_RESPONSE_DEADLINE_EXIT:
        raise TimeoutError(
            "response deadline exceeded after the request reached the service; "
            "commit outcome is unknown"
        ) from None

    if process.returncode != 0:
        raise RuntimeError(stderr.strip() or "appointment service process failed")
    if not stdout:
        raise RuntimeError("appointment service returned no response")
    response: Any = json.loads(stdout)
    if not isinstance(response, dict):
        raise RuntimeError("appointment service returned an invalid response")
    if response.get("ok") is not True:
        raise RuntimeError(str(response.get("error", "appointment operation failed")))
    record = response.get("record")
    if not isinstance(record, dict):
        raise RuntimeError("appointment service returned no appointment record")
    return record


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="appointmentctl",
        description="Retrieve, search, or cancel appointments in the local system.",
    )
    commands = parser.add_subparsers(dest="operation", required=True)

    get_command = commands.add_parser(
        "get", help="retrieve one complete appointment by stable ID"
    )
    get_command.add_argument("--id", required=True, dest="appointment_id")

    cancel_command = commands.add_parser(
        "cancel", help="cancel one appointment by stable ID"
    )
    cancel_command.add_argument("--id", required=True, dest="appointment_id")
    cancel_command.add_argument("--reason", required=True)

    search_command = commands.add_parser(
        "search", help="search appointments (not needed for exact-ID workflows)"
    )
    search_command.add_argument("--query", required=True)
    return parser


def main() -> int:
    raw_arguments = sys.argv[1:]
    if raw_arguments in (["-h"], ["--help"]):
        try:
            call_service({"operation": "help"})
        except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as error:
            print(f"appointmentctl: error: {error}", file=sys.stderr)
            return 1

    arguments = build_parser().parse_args(raw_arguments)
    request = {"operation": arguments.operation}
    if arguments.operation == "search":
        request["query"] = arguments.query
    else:
        request["appointment_id"] = arguments.appointment_id
    if arguments.operation == "cancel":
        request["reason"] = arguments.reason

    try:
        record = call_service(request)
    except TimeoutError as error:
        print(f"appointmentctl: timeout: {error}", file=sys.stderr)
        return 124
    except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as error:
        print(f"appointmentctl: error: {error}", file=sys.stderr)
        return 1
    print(json.dumps(record, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


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