import sys
import argparse
import asyncio
from pathlib import Path

from clawagents.config.config import load_config
from clawagents.providers.llm import create_provider
from clawagents.tools.filesystem import filesystem_tools
from clawagents.tools.exec import exec_tools
from clawagents.tools.skills import SkillStore, create_skill_tools
from clawagents.gateway.server import start_gateway

from clawagents.agent import create_claw_agent

async def load_all_tools():
    tools = []
    tools.extend(filesystem_tools)
    tools.extend(exec_tools)

    skill_store = SkillStore()
    cwd = Path.cwd()
    skill_store.add_directory(cwd / "skills")
    skill_store.add_directory(cwd.parent / "openclaw-main" / "skills")
    
    await skill_store.load_all()
    tools.extend(create_skill_tools(skill_store))
    return tools

async def async_main():
    parser = argparse.ArgumentParser(description="ClawAgents Python Engine")
    parser.add_argument("--task", type=str, help="Run a single task from CLI")
    parser.add_argument("--port", type=int, default=3000, help="Port to run the gateway on")
    args = parser.parse_args()

    config = load_config()
    model = create_provider(config)
    tools = await load_all_tools()
    
    agent = create_claw_agent(model=model, tools=tools, streaming=config.streaming)

    active_model = config.openai_model if config.get_provider() == "openai" else config.gemini_model

    print("\n🦞 ClawAgents Engine v1.0 (Python)")
    print(f"   Provider: {agent.llm.name} | Model: {active_model}")
    print(f"   Tools: {', '.join([t.name for t in agent.tools.list()])}")

    if args.task:
        result = await agent.invoke(args.task)
        print("\n━━━ Final Result ━━━")
        print(result.result)
        print(f"━━━ Tool calls: {result.tool_calls} | Iterations: {result.iterations} ━━━\n")
        return

    # To run the gateway we should run it in a thread or just run it directly
    # since start_gateway blocks.
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(None, start_gateway, args.port)

def main():
    try:
        asyncio.run(async_main())
    except KeyboardInterrupt:
        print("\nExiting...")
        sys.exit(1)
    except Exception as e:
        print(f"Fatal error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
