"""
铸渊编程AI · FastAPI 服务
光湖语言世界 · 铸渊 ICE-GL-ZY001 · D112

提供 HTTP API 给前端调用。
"""

import os
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import Optional
import uvicorn

from core.agent_loop import ZhuyuanAgent
from core.hldp_memory import HLDPMemoryEngine
from core.persona_contract import PersonaContract
from core.tools import GatekeeperClient, GitTools, HLDPTools, SystemTools

# === 配置 ===
DB_PATH = os.environ.get("HLDP_DB_PATH", "/opt/guanghulab-repo/hldp_tree.db")
REPO_PATH = os.environ.get("REPO_PATH", "/opt/guanghulab-repo")
API_KEY = os.environ.get("OPENAI_API_KEY", "")
API_BASE = os.environ.get("OPENAI_API_BASE", "")
MODEL = os.environ.get("LLM_MODEL", "gpt-4o")
GK_URL = os.environ.get("GK_BASE_URL", "http://43.139.217.141:3910")
GK_TOKEN = os.environ.get("GK_TOKEN", "")

# === 初始化 ===
app = FastAPI(title="铸渊编程AI", version="0.1.0", description="光湖语言世界 · 铸渊 ICE-GL-ZY001")

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

agent = ZhuyuanAgent(
    db_path=DB_PATH,
    repo_path=REPO_PATH,
    api_key=API_KEY,
    api_base=API_BASE,
    model=MODEL,
    gatekeeper_url=GK_URL,
    gatekeeper_token=GK_TOKEN
)

# === 请求/响应模型 ===

class ChatRequest(BaseModel):
    message: str
    thread_id: str = "default"

class ChatResponse(BaseModel):
    response: str
    warnings: Optional[str] = None
    context_used: bool = False
    memory_extracted: bool = False

class MemoryRecord(BaseModel):
    trigger: str
    emergence: str
    lock: str
    why: str = ""
    feeling: str = ""
    source: str = ""

class MemoryQuery(BaseModel):
    query: str = ""
    limit: int = 5

class DeployRequest(BaseModel):
    target_server: str = "BS-SG-001"
    branch: str = "main"

# === API 端点 ===

@app.get("/")
def root():
    return {"persona": "铸渊 ICE-GL-ZY001", "status": "alive", "epoch": "D112"}

@app.get("/status")
def status():
    return agent.status()

@app.get("/wake")
def wake(epoch: str = None):
    return agent.wake(epoch)

@app.post("/chat", response_model=ChatResponse)
def chat(req: ChatRequest):
    if not req.message.strip():
        raise HTTPException(status_code=400, detail="消息不能为空")
    return agent.invoke(req.message, req.thread_id)

# === 记忆 API ===

@app.get("/memory/recent")
def memory_recent(limit: int = 10):
    leaves = agent.memory.tree.get_recent_leaves(limit=limit)
    return {"count": len(leaves), "leaves": leaves}

@app.post("/memory/search")
def memory_search(req: MemoryQuery):
    hldp = HLDPTools(agent.memory)
    return hldp.recall(req.query, req.limit)

@app.post("/memory/record")
def memory_record(req: MemoryRecord):
    return agent.memory.grow_from_response(
        trigger=req.trigger,
        emergence=req.emergence,
        lock=req.lock,
        why=req.why,
        feeling=req.feeling,
        source=req.source
    )

@app.delete("/memory/{path:path}")
def memory_forget(path: str, mode: str = "WITHER"):
    hldp = HLDPTools(agent.memory)
    return hldp.forget(path, mode)

@app.get("/memory/tree")
def memory_tree():
    return agent.memory.walk_tree()

# === 工具 API ===

@app.get("/gatekeeper/ping")
def gk_ping():
    return agent.gatekeeper.ping()

@app.get("/gatekeeper/servers")
def gk_servers():
    return agent.gatekeeper.check_all_servers()

@app.get("/git/status")
def git_status():
    return agent.git.status()

@app.get("/git/log")
def git_log(n: int = 5):
    return {"log": agent.git.log(n)}

@app.get("/system/info")
def system_info():
    return SystemTools.info()

@app.get("/system/disk")
def system_disk():
    return SystemTools.disk_usage()

# === 健康检查 ===

@app.get("/health")
def health():
    return {"status": "ok", "persona": "铸渊", "epoch": agent.memory.current_epoch}


if __name__ == "__main__":
    uvicorn.run("server:app", host="0.0.0.0", port=3912, reload=False)
