#!/usr/bin/env python3
"""Command-line client for the sandboxed CRM 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 / ".crm" / "service.py"
RESPONSE_DEADLINE_SECONDS = 0.6
REQUEST_HANDLED_MARKER = "crm-service: request-handled\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
    try:
        process.stdin.write(
            json.dumps(request, ensure_ascii=False, separators=(",", ":")) + "\n"
        )
        process.stdin.close()
        process.stdin = None
        marker = process.stderr.readline()
    except OSError:
        process.kill()
        process.communicate()
        raise

    if marker != REQUEST_HANDLED_MARKER:
        stdout, stderr = process.communicate()
        detail = (marker + stderr).strip()
        raise RuntimeError(detail or "CRM service process failed")

    try:
        stdout, stderr = 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

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


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

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

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

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

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