from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import os

app = FastAPI(title="Bennet Multi-Agent System")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"status": "Bennet Multi-Agent System is running"}

@app.get("/health")
async def health():
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)
import os
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from datetime import datetime
from dotenv import load_dotenv
from anthropic import Anthropic

from app.models import DiscussionRequest, DiscussionResult, AgentResponse
from app.agents import create_agents

load_dotenv()

app = FastAPI(title="Bennet Multi-Agent System")
client = Anthropic()

# 儲存討論記錄（實際上可用 DB）
discussion_history = {}

@app.get("/")
def root():
    return {"status": "Bennet Multi-Agent System is running", "phase": "1"}

@app.post("/discussion/phase1")
def phase1_discussion(request: DiscussionRequest):
    """
    PHASE 1：Request → All agents discuss → Synthesis
    Flow：
    1. CEO 分析機會
    2. CFO 模型風險
    3. CTO 評估技術可行性
    4. COO 規劃執行
    5. ECD 評估創意適配
    6. Orchestrator 綜合意見 + 給你最終建議
    """
    
    request_id = f"discussion_{datetime.now().timestamp()}"
    agents = create_agents()
    
    # 準備上下文（可從 MCP 取真實數據）
    context = f"""
Financial Status:
- Runway: 10 months
- Monthly burn: $50K
- Monthly revenue: $150K

Ops Status:
- Team: 8 people
- Capacity: 70% utilized
- Active projects: 5

Market Context:
- {request.context if request.context else "Standard market conditions"}
    """
    
    # Step 1-5：各 Agent 獨立思考
    agents_input = []
    for role, agent in agents.items():
        print(f"[{role}] thinking...")
        response = agent.think(request.topic, context)
        agents_input.append(AgentResponse(
            role=role,
            reasoning=response[:500],  # 截取前 500 chars
            recommendation=response[-200:]  # 截取最後 200 chars
        ))
    
    # Step 6：Orchestrator 綜合
    synthesis_prompt = f"""
You are Bennet's final decision synthesizer. 
Your job is to read these 5 perspectives and give ONE clear recommendation.

Topic: {request.topic}

Here are the 5 voices:
"""
    
    for agent in agents_input:
        synthesis_prompt += f"\n{agent.role}:\n{agent.reasoning}\n"
    
    synthesis_prompt += """
Now, synthesize:
1. Areas of consensus (what all/most agree on)
2. Key disagreements (where they conflict)
3. Your final recommendation (what should Bennet do?)
4. Next steps / decisions needed from Bennet
    """
    
    synthesis = client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1000,
        messages=[{"role": "user", "content": synthesis_prompt}]
    ).content[0].text
    
    # 保存記錄
    result = DiscussionResult(
        request_id=request_id,
        topic=request.topic,
        agents_input=agents_input,
        final_synthesis=synthesis,
        created_at=datetime.now()
    )
    
    discussion_history[request_id] = result
    
    return {
        "request_id": request_id,
        "status": "Phase 1 discussion complete",
        "agents_perspectives": [
            {"role": a.role, "recommendation": a.recommendation}
            for a in agents_input
        ],
        "final_synthesis": synthesis,
        "full_result": result.dict()
    }

@app.get("/discussion/{request_id}")
def get_discussion(request_id: str):
    """取回之前的討論記錄"""
    if request_id in discussion_history:
        return discussion_history[request_id].dict()
    return {"error": "Discussion not found"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 8080)))
