"""koa-fhe CLI — ephemeral agent interface to Koa's confidential coprocessor.

Designed for agent-to-agent interactions where the caller doesn't want to
manage a Python environment. Every command outputs JSON to stdout.

    uvx koa-fhe health
    uvx koa-fhe compare 85 80
    uvx koa-fhe add 500 300
    uvx koa-fhe multiply 7 13
    uvx koa-fhe verify --circuit add --queries 3
"""

from __future__ import annotations

import argparse
import dataclasses
import json
import sys


def _to_dict(obj):
    """Convert a dataclass (possibly nested) to JSON-serializable dict."""
    if dataclasses.is_dataclass(obj):
        d = {}
        for f in dataclasses.fields(obj):
            d[f.name] = _to_dict(getattr(obj, f.name))
        return d
    if isinstance(obj, list):
        return [_to_dict(item) for item in obj]
    return obj


def _out(obj):
    """Print JSON to stdout."""
    if dataclasses.is_dataclass(obj):
        obj = _to_dict(obj)
    print(json.dumps(obj, indent=2))


def _client(args):
    from . import Client
    return Client(args.server)


def cmd_health(args):
    _out(_client(args).health())


def cmd_circuits(args):
    _out(_client(args).circuits())


def cmd_compare(args):
    _out(_client(args).compare(args.a, args.b))


def cmd_add(args):
    _out(_client(args).add(args.a, args.b))


def cmd_multiply(args):
    _out(_client(args).multiply(args.a, args.b))


def cmd_verify(args):
    result = _client(args).verify_integrity(
        args.circuit, args.queries, seed=args.seed
    )
    _out(result)
    if not result.passed:
        sys.exit(1)


def cmd_version(args):
    from . import __version__
    print(json.dumps({"version": __version__}))


def main():
    p = argparse.ArgumentParser(
        prog="koa-fhe",
        description="Confidential coprocessor — compute on encrypted data via FHE.",
    )
    p.add_argument(
        "--server", default="http://127.0.0.1:3410",
        help="FHE service URL (default: http://127.0.0.1:3410)",
    )
    sub = p.add_subparsers(dest="command")

    # health
    sub.add_parser("health", help="Check FHE service status")

    # circuits
    sub.add_parser("circuits", help="List available circuits with pricing")

    # compare
    cmp = sub.add_parser("compare", help="Encrypted comparison: is a > b?")
    cmp.add_argument("a", type=int)
    cmp.add_argument("b", type=int)

    # add
    add = sub.add_parser("add", help="Encrypted addition: a + b")
    add.add_argument("a", type=int)
    add.add_argument("b", type=int)

    # multiply
    mul = sub.add_parser("multiply", help="Encrypted multiplication: a * b")
    mul.add_argument("a", type=int)
    mul.add_argument("b", type=int)

    # verify
    ver = sub.add_parser("verify", help="Run trap queries (integrity check)")
    ver.add_argument("--circuit", default="add", choices=["add", "multiply", "threshold"])
    ver.add_argument("--queries", type=int, default=3, help="Number of trap queries")
    ver.add_argument("--seed", type=int, default=None, help="RNG seed for reproducibility")

    # version
    sub.add_parser("version", help="Show SDK version")

    args = p.parse_args()
    if not args.command:
        p.print_help()
        sys.exit(1)

    dispatch = {
        "health": cmd_health,
        "circuits": cmd_circuits,
        "compare": cmd_compare,
        "add": cmd_add,
        "multiply": cmd_multiply,
        "verify": cmd_verify,
        "version": cmd_version,
    }
    dispatch[args.command](args)
