"""
Brynq Enterprise Control Plane API
Handles RBAC, Vault Injection, and Crew Spawning.
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import uuid

# Internal Brynq Imports
from brynq.licensing_engine import LicensingEngine
from brynq.personality import assign_personality, list_templates

app = FastAPI(title="Brynq Enterprise", version="1.0.0")
license_engine = LicensingEngine()

class AgentConfig(BaseModel):
    model: str
    personality_template: str

class CrewSpawnRequest(BaseModel):
    crew_name: str
    agents: List[AgentConfig]

@app.post("/api/v1/crews/spawn")
def spawn_enterprise_crew(req: CrewSpawnRequest):
    if not license_engine.can_spawn_agents(len(req.agents)):
        raise HTTPException(
            status_code=403, 
            detail=f"License limit exceeded. {license_engine.tier.name} allows max {license_engine.tier.max_agents} agents."
        )
    
    spawned_agents = []
    for agent in req.agents:
        session_id = f"agent_{uuid.uuid4().hex[:8]}"
        try:
            # Wire into the new Personality architecture
            assigned = assign_personality(agent.personality_template, session_id=session_id)
            spawned_agents.append({
                "session_id": session_id,
                "model": agent.model,
                "personality": assigned["personality"]["name"]
            })
        except ValueError as e:
            raise HTTPException(status_code=400, detail=str(e))
            
    return {
        "status": "Crew dispatched to Compute Grid",
        "crew_name": req.crew_name,
        "agents": spawned_agents,
        "vault_status": "Unlocked" if license_engine.tier.vault_access else "Locked"
    }
