import json
from fastapi import FastAPI, Request, Response
import uvicorn

from clawagents.config.config import load_config
from clawagents.providers.llm import create_provider
from clawagents.process.command_queue import enqueue_command
from clawagents.agent import create_claw_agent
from clawagents.tools.filesystem import filesystem_tools
from clawagents.tools.exec import exec_tools

def create_app() -> FastAPI:
    config = load_config()
    llm = create_provider(config)
    active_model = config.openai_model if config.get_provider() == "openai" else config.gemini_model
    
    app = FastAPI(title="ClawAgents Gateway")

    @app.get("/health")
    async def health():
        return {"status": "ok", "provider": llm.name, "model": active_model}

    @app.post("/chat")
    async def chat(request: Request):
        try:
            payload = await request.json()
        except:
            return Response(
                content=json.dumps({"error": "Invalid JSON. Send { \"task\": \"your task here\" }"}),
                status_code=400,
                media_type="application/json"
            )
            
        task = payload.get("task", "Unknown task")
        
        async def execute_graph():
            print(f"[Gateway] Processing task: {task}")
            
            # Simplified tool loading for default HTTP gateway
            # Production deployments pass SkillStores via args
            tools = filesystem_tools + exec_tools
            agent = create_claw_agent(model=llm, tools=tools)
            
            final_state = await agent.invoke(task)
            return final_state

        try:
            result = await enqueue_command(execute_graph)
            return {
                "success": True,
                "status": result.status,
                "result": result.result,
                "iterations": result.iterations
            }
        except Exception as e:
            return Response(
                content=json.dumps({"success": False, "error": str(e)}),
                status_code=500,
                media_type="application/json"
            )

    return app, llm, active_model


def start_gateway(port: int = 3000):
    app, llm, active_model = create_app()
    print(f"\n🦞 ClawAgents Gateway running on http://localhost:{port}")
    print(f"   Provider: {llm.name}")
    print(f"   Model: {active_model}")
    print("   Endpoints: POST /chat | GET /health\n")
    
    uvicorn.run(app, host="0.0.0.0", port=port, log_level="warning")
