"""Command-line interface for Plan-and-Solve agent."""

import argparse
import json

from .agent import PlanAndSolveAgent, PSResult


def create_demo_agent() -> PlanAndSolveAgent:
    """Create a demo agent with simple functions."""
    def plan_fn(problem: str) -> list:
        # Demo plan generator
        return [
            "Analyze the problem requirements",
            "Identify key components",
            "Develop solution approach",
            "Execute the solution",
            "Verify the result",
        ]

    def solve_fn(step: str, context: dict) -> str:
        # Demo solver
        problem = context.get("problem", "")
        step_results = context.get("step_results", {})

        # Simulate step execution
        if "analyze" in step.lower():
            return f"Analysis: {problem[:50]}..."
        elif "identify" in step.lower():
            return "Key components identified"
        elif "develop" in step.lower():
            return "Solution approach: step-by-step execution"
        elif "execute" in step.lower():
            return "Execution completed successfully"
        else:
            return "Verification passed"

    return PlanAndSolveAgent(
        plan_fn=plan_fn,
        solve_fn=solve_fn,
        verbose=True,
    )


def run_task(args: argparse.Namespace) -> None:
    """Run a single task."""
    agent = create_demo_agent()
    result = agent.solve(args.problem)

    print("\n" + "=" * 50)
    print(f"Success: {result.success}")
    print(f"Answer: {result.answer}")
    print(f"Time: {result.trajectory.total_time:.2f}s")

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


def interactive_mode(args: argparse.Namespace) -> None:
    """Run in interactive mode."""
    agent = create_demo_agent()

    print("Plan-and-Solve Agent Interactive Mode")
    print("Type 'quit' to exit, 'plan' to see last plan")
    print("-" * 50)

    last_result = None

    while True:
        try:
            problem = input("\nProblem: ").strip()
        except (EOFError, KeyboardInterrupt):
            print("\nGoodbye!")
            break

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

        if problem.lower() == "plan" and last_result:
            if last_result.plan:
                print("\n" + last_result.plan.to_prompt())
            continue

        if not problem:
            continue

        result = agent.solve(problem)
        last_result = result
        print(f"\nAnswer: {result.answer}")


def main() -> None:
    """Main entry point."""
    parser = argparse.ArgumentParser(
        description="Plan-and-Solve Agent - Improved Zero-Shot Reasoning"
    )
    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # Run command
    run_parser = subparsers.add_parser("run", help="Run a single problem")
    run_parser.add_argument("problem", help="Problem to solve")
    run_parser.add_argument("--export", "-e", help="Export result to JSON")

    # Interactive command
    subparsers.add_parser("interactive", help="Start interactive mode")

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

    args = parser.parse_args()

    if args.command == "run":
        run_task(args)
    elif args.command == "interactive":
        interactive_mode(args)
    elif args.command == "status":
        print("Plan-and-Solve Agent v0.1.0")
        print("Implementation of arxiv:2305.04091")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()