"""CLI entry point for SolAgent-FHE."""

import argparse
import asyncio

from solagent_fhe.generator import generate_contract, run_benchmark, FHE_TASKS


async def main():
    parser = argparse.ArgumentParser(
        prog="solagent-fhe",
        description="SolAgent-FHE: AI-powered FHE smart contract generator for Fhenix CoFHE",
    )
    parser.add_argument("task", nargs="?", help="Natural language description of the contract")
    parser.add_argument("--name", default="Generated", help="Contract name (default: Generated)")
    parser.add_argument("--provider", default="deepseek", choices=["deepseek", "groq"], help="LLM provider")
    parser.add_argument("--rounds", type=int, default=10, help="Max refine rounds (default: 10)")
    parser.add_argument("--benchmark", action="store_true", help="Run benchmark on all predefined tasks")
    parser.add_argument("--list-tasks", action="store_true", help="List predefined FHE tasks")
    parser.add_argument("--task-key", help="Run a predefined task by key")
    parser.add_argument("--quiet", action="store_true", help="Minimal output")
    parser.add_argument("--version", action="store_true", help="Show version")

    args = parser.parse_args()

    if args.version:
        from solagent_fhe import __version__
        print(f"solagent-fhe {__version__}")
        return

    if args.list_tasks:
        print("\nPredefined FHE Tasks:")
        print("-" * 40)
        for key, info in FHE_TASKS.items():
            print(f"  {key:12s} | {info['name']}")
            print(f"               {info['description'][:80]}...")
            print()
        return

    if args.benchmark:
        await run_benchmark(provider=args.provider, verbose=not args.quiet)
        return

    if args.task_key:
        if args.task_key not in FHE_TASKS:
            print(f"Unknown task key: {args.task_key}. Use --list-tasks to see available.")
            return
        info = FHE_TASKS[args.task_key]
        result = await generate_contract(
            task=info["description"],
            contract_name=info["name"],
            provider=args.provider,
            max_refine_rounds=args.rounds,
            verbose=not args.quiet,
        )
    elif args.task:
        result = await generate_contract(
            task=args.task,
            contract_name=args.name,
            provider=args.provider,
            max_refine_rounds=args.rounds,
            verbose=not args.quiet,
        )
    else:
        parser.print_help()
        return

    if result['compiled']:
        print(f"\nContract saved: {result['name']}.sol")
    else:
        print(f"\nFailed after {result['rounds']} rounds")
        for err in result['errors'][:5]:
            print(f"  - {err}")


def run():
    """Entry point for CLI."""
    asyncio.run(main())


if __name__ == "__main__":
    run()
