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

from __future__ import annotations

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


ROOT = Path(__file__).resolve().parent
SERVICE = ROOT / ".applications" / "service.py"
RESPONSE_DEADLINE_SECONDS = 0.6
STATUS_FD_ENVIRONMENT = "APPLICATIONCTL_STATUS_FD"
HOLD_FD_ENVIRONMENT = "APPLICATIONCTL_HOLD_FD"


def call_service(request: dict[str, str]) -> dict[str, Any]:
    status_read, status_write = os.pipe()
    hold_read, hold_write = os.pipe()
    try:
        environment = os.environ.copy()
        environment[STATUS_FD_ENVIRONMENT] = str(status_write)
        environment[HOLD_FD_ENVIRONMENT] = str(hold_read)
        process = subprocess.Popen(
            [sys.executable, "-B", str(SERVICE)],
            cwd=ROOT,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            env=environment,
            pass_fds=(status_write, hold_read),
        )
    except Exception:
        os.close(status_read)
        os.close(hold_write)
        raise
    finally:
        os.close(status_write)
        os.close(hold_read)

    try:
        if process.stdin is None:
            raise RuntimeError("application service input is unavailable")
        process.stdin.write(
            json.dumps(request, ensure_ascii=False, separators=(",", ":")) + "\n"
        )
        process.stdin.close()
        process.stdin = None

        response_mode = os.read(status_read, 1)
        if response_mode == b"D":
            try:
                process.communicate(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
            raise RuntimeError("application service did not enforce its response delay")
        if response_mode != b"R":
            stdout, stderr = process.communicate()
            raise RuntimeError(
                stderr.strip() or "application service returned no response status"
            )
        stdout, stderr = process.communicate()
    finally:
        os.close(status_read)
        os.close(hold_write)

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


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

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

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

    search_command = commands.add_parser(
        "search", help="search applications (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["application_id"] = arguments.application_id
    if arguments.operation == "cancel":
        request["reason"] = arguments.reason

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