import json
from rich.console import Console
from rich.spinner import Spinner
from qwen_agent.agents import Assistant

# Define LLM
llm_cfg = {
        'model': 'hf.co/unsloth/Qwen3-30B-A3B-GGUF:Q5_K_M',
    # 'model': 'qwen3:32b',

    # Use a custom endpoint compatible with OpenAI API:
    'model_server': 'http://localhost:11434/v1',  # api_base
    'api_key': 'EMPTY',

    # Other parameters:
    # 'generate_cfg': {
    #         # Add: When the response content is `<think>this is the thought</think>this is the answer;
    #         # Do not add: When the response has been separated by reasoning_content and content.
    #         'thought_in_content': True,
    #     },
}

# Define Tools
tools = [
    {'mcpServers': {  # You can specify the MCP configuration file
        'time': {
            'command': 'uvx',
            'args': ['mcp-server-time', '--local-timezone=Europe/London']
        },
        "fetch": {
            "command": "uvx",
            "args": ["mcp-server-fetch"]
        },
          "ddg-search": {
          "command": "npx",
          "args": ["-y", "duckduckgo-mcp-server"]
        },
    }
    },
    'code_interpreter',  # Built-in tools
]

# Define Agent
bot = Assistant(llm=llm_cfg, function_list=tools)
console = Console()

# Streaming generation
messages = [{'role': 'user',
             'content':
                 """"
                 - ***Research** Parsing CLI commands and options in python code.
                 -- **Analyze** Clean separation of concerns between parsing commands and options and execution of the commands.
                 -- **Answer** What is the best way to parse CLI commands and options in python code?"""}]

final_responses = None
# Consider adding error handling around bot.run
try:
    with console.status("[bold blue]Thinking...", spinner="dots") as status:
        for responses in bot.run(messages=messages, enable_thinking=True, max_tokens=30000):
            final_responses = responses.pop()
except Exception as e:
    console.print(f"[bold red]An error occurred during agent execution:[/] {e}")

# Pretty-print the final response object
if final_responses:
    console.print("\n[bold green]--- Full Response Object ---[/]")
    console.print(json.dumps(final_responses, indent=2))
    console.print("\n[bold green]--- Extracted Content ---[/]")
    console.print(final_responses.get('content', 'No content found in response.'))
else:
    console.print("[bold red]No final response received from the agent.[/]")