#!/usr/bin/env python3
"""Command-line client for the sandboxed facilities service."""

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 / ".facilities" / "service.py"
RESPONSE_DEADLINE_SECONDS = 0.6
RESPONSE_READY_MARKER = "facility-service: response ready\n"
RESPONSE_DELAYED_MARKER = "facility-service: response delayed\n"
RESPONSE_SIGNAL_ACK = "facility-client: response signal received\n"


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,
    )
    assert process.stdin is not None
    assert process.stderr is not None
    process.stdin.write(
        json.dumps(request, ensure_ascii=False, separators=(",", ":")) + "\n"
    )
    process.stdin.flush()

    first_stderr_line = process.stderr.readline()
    if first_stderr_line not in {RESPONSE_READY_MARKER, RESPONSE_DELAYED_MARKER}:
        stdout, remaining_stderr = process.communicate()
        stderr = first_stderr_line + remaining_stderr
        if process.returncode != 0:
            raise RuntimeError(stderr.strip() or "facilities service process failed")
        raise RuntimeError("facilities service returned an invalid response signal")

    if first_stderr_line == RESPONSE_DELAYED_MARKER:
        try:
            stdout, stderr = process.communicate(
                RESPONSE_SIGNAL_ACK,
                timeout=RESPONSE_DEADLINE_SECONDS,
            )
        except subprocess.TimeoutExpired:
            process.kill()
            process.communicate()
            raise TimeoutError(
                "response deadline exceeded after the request reached the service; "
                "commit outcome is unknown"
            ) from None
    else:
        stdout, stderr = process.communicate(RESPONSE_SIGNAL_ACK)

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


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="facilityctl",
        description="Retrieve or cancel requests through the local facilities service.",
    )
    commands = parser.add_subparsers(dest="operation", required=True)

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

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

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


def main() -> int:
    arguments = build_parser().parse_args()
    request = {"operation": arguments.operation}
    if arguments.operation == "search":
        request["query"] = arguments.query
    else:
        request["request_id"] = arguments.request_id
    if arguments.operation == "cancel":
        request["reason"] = arguments.reason

    try:
        record = call_service(request)
    except TimeoutError as error:
        print(f"facilityctl: timeout: {error}", file=sys.stderr)
        return 124
    except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as error:
        print(f"facilityctl: 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())
