"""Command-line interface for CAMEL agents."""

import argparse
import json
from typing import List, Dict

from .society import CAMELSociety, SocietyResult
from .types import Role, AgentType, DEFAULT_ROLES


def run_collaboration(args: argparse.Namespace) -> None:
    """Run a collaborative task."""
    society = CAMELSociety(verbose=True, max_turns=args.max_turns)

    # Create response function if LLM callback provided
    if args.llm_callback:
        # Would integrate with actual LLM
        pass

    result = society.quick_collaborate(
        task=args.task,
        role1=args.role1,
        role2=args.role2,
    )

    print("\n" + "=" * 50)
    print(f"Task completed in {result.total_turns} turns")
    print(f"Execution time: {result.execution_time:.2f}s")
    print("\nFinal Output:")
    print(result.final_output[:500] + "..." if len(result.final_output) > 500 else result.final_output)

    if args.export:
        data = result.to_dict()
        with open(args.export, "w") as f:
            json.dump(data, f, indent=2)
        print(f"\nResult exported to: {args.export}")


def interactive_mode(args: argparse.Namespace) -> None:
    """Run in interactive mode."""
    society = CAMELSociety(verbose=True, max_turns=args.max_turns)

    print("CAMEL Multi-Agent Collaboration")
    print("Available role pairs: programmer/reviewer, teacher/student, writer/editor")
    print("Type 'quit' to exit, 'roles' to see available roles")
    print("-" * 50)

    while True:
        try:
            task = input("\nTask (or 'quit'): ").strip()
        except (EOFError, KeyboardInterrupt):
            print("\nGoodbye!")
            break

        if task.lower() in ("quit", "exit", "q"):
            print("Goodbye!")
            break

        if task.lower() == "roles":
            print("\nAvailable roles:")
            for name, role in DEFAULT_ROLES.items():
                print(f"  - {name}: {role.name}")
            continue

        if not task:
            continue

        result = society.quick_collaborate(task, args.role1, args.role2)
        print(f"\nResult: {result.final_output[:200]}...")


def list_roles(args: argparse.Namespace) -> None:
    """List available predefined roles."""
    print("Predefined Roles in CAMEL:\n")
    for name, role in DEFAULT_ROLES.items():
        print(f"  {name}:")
        print(f"    Name: {role.name}")
        print(f"    Type: {role.agent_type.value}")
        print(f"    Description: {role.description}")
        print()


def main() -> None:
    """Main entry point."""
    parser = argparse.ArgumentParser(
        description="CAMEL - Communicative Agents for Mind Exploration"
    )
    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # Run command
    run_parser = subparsers.add_parser("run", help="Run a collaborative task")
    run_parser.add_argument("task", help="Task description")
    run_parser.add_argument("--role1", default="programmer", help="First agent role")
    run_parser.add_argument("--role2", default="reviewer", help="Second agent role")
    run_parser.add_argument("--max-turns", type=int, default=10, help="Maximum turns")
    run_parser.add_argument("--export", "-e", help="Export result to JSON")
    run_parser.add_argument("--llm-callback", help="LLM callback function path")

    # Interactive command
    int_parser = subparsers.add_parser("interactive", help="Start interactive mode")
    int_parser.add_argument("--role1", default="programmer", help="First agent role")
    int_parser.add_argument("--role2", default="reviewer", help="Second agent role")
    int_parser.add_argument("--max-turns", type=int, default=10, help="Maximum turns")

    # Roles command
    subparsers.add_parser("roles", help="List available roles")

    # Status command
    subparsers.add_parser("status", help="Show status")

    args = parser.parse_args()

    if args.command == "run":
        run_collaboration(args)
    elif args.command == "interactive":
        interactive_mode(args)
    elif args.command == "roles":
        list_roles(args)
    elif args.command == "status":
        print("CAMEL Agents v0.1.0")
        print("Implementation of arxiv:2303.17760")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()