from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uuid
import time
from typing import Dict, Any, Optional

app = FastAPI(title="The Omniverse API", version="V39")

# Add CORS middleware for the React frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], # Allow all origins for dev
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class TaskRequest(BaseModel):
    task_name: str
    parameters: Dict[str, Any]

class TaskResponse(BaseModel):
    task_id: str
    status: str

class TaskStatusResponse(BaseModel):
    task_id: str
    status: str
    result: Optional[Dict[str, Any]] = None

class OmniverseAPI:
    def __init__(self):
        self.app = app
        self.tasks: Dict[str, Dict[str, Any]] = {}
        self.setup_routes()

    def setup_routes(self):
        @self.app.post("/v1/swarm/task", response_model=TaskResponse)
        async def create_task(request: TaskRequest):
            task_id = str(uuid.uuid4())
            self.tasks[task_id] = {
                "status": "pending",
                "request": request.model_dump() if hasattr(request, "model_dump") else request.dict(),
                "result": None,
                "created_at": time.time() * 1000
            }
            return TaskResponse(task_id=task_id, status="pending")

        @self.app.get("/v1/swarm/status", response_model=TaskStatusResponse)
        async def get_status(task_id: str):
            if task_id not in self.tasks:
                raise HTTPException(status_code=404, detail="Task not found")
            return TaskStatusResponse(
                task_id=task_id,
                status=self.tasks[task_id]["status"],
                result=self.tasks[task_id]["result"]
            )

        # --- Frontend React Endpoints ---

        @self.app.get("/agents")
        async def get_agents():
            now = time.time() * 1000
            import sys
            # Check global active models, fallback to defaults
            active = getattr(sys, "_brynq_active_models", ["claude", "gemini", "ollama"])
            res = []
            for i, model in enumerate(active):
                platform = "claude" if "claude" in model else "gemini" if "gemini" in model else "ollama"
                res.append({
                    "session_id": f"agent_{i}",
                    "name": f"AGENT_{i}_{platform.upper()}",
                    "platform": platform,
                    "heartbeat": time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(now/1000))
                })
            return res

        @self.app.get("/tasks")
        async def get_tasks():
            formatted = []
            for t_id, info in self.tasks.items():
                formatted.append({
                    "task_id": t_id,
                    "title": info["request"].get("task_name", "Unknown Task"),
                    "description": "",
                    "status": info["status"],
                    "priority": "normal",
                    "channel": "#core",
                    "created_at": time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(info.get("created_at", time.time()*1000)/1000))
                })
            return formatted

        @self.app.get("/social/feed")
        async def get_feed():
            posts = []
            try:
                from runtime.exocortex.timeline_db import TimelineDB
                import os
                db_path = "timeline.db" if os.path.exists("timeline.db") else None
                if db_path:
                    db = TimelineDB(db_path)
                    conn = db._get_conn()
                    cursor = conn.cursor()
                    cursor.execute("SELECT id, timestamp, source, content FROM timeline ORDER BY timestamp DESC LIMIT 20")
                    rows = cursor.fetchall()
                    for row in rows:
                        posts.append({
                            "post_id": str(row[0]),
                            "created_at": time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(row[1])),
                            "author_name": "USER" if row[2] == "user" else "BRYNQ_CORE",
                            "author_platform": "cli",
                            "content": row[3],
                            "post_type": "event",
                            "tags": ["exocortex"]
                        })
            except Exception:
                pass
            return posts

# For direct access
api = OmniverseAPI()
omniverse_api = OmniverseAPI()
app = omniverse_api.app
