import sys
sys.path.insert(0, '/opt/guanghulab-repo/zhuyuan-agent')

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional, List
import os, json, time

from core.hldp_memory import HLDPMemoryEngine, PERSONA_ID, HLDP_ROOT
from core.persona_contract import pre_check_context, post_check_warnings

app = FastAPI(title='铸渊 Agent API', version='1.0.0')
engine = HLDPMemoryEngine()
startup_msg = engine.wake()
print(f'[铸渊] {startup_msg["status"]}')
tree = engine.tree

class ChatRequest(BaseModel):
    message: str
    user_id: Optional[str] = 'ice-shuo'

class MemoryRecord(BaseModel):
    path: str
    trigger: str
    emergence: str
    lock_value: str
    why: str = ''

class MemorySearch(BaseModel):
    query: str
    limit: int = 10

@app.get('/health')
async def health():
    return {'status': 'ok', 'persona': '铸渊', 'epoch': 'D112', 'time': time.time()}

@app.get('/status')
async def status():
    w = tree.walk_tree(PERSONA_ID, max_depth=3)
    return {'status': 'running', 'tree_layers': {
        'root': str(w.get('layer_0_root',''))[:80],
        'epochs': len(w.get('layer_1_epochs', [])),
        'leaves': len(w.get('layer_2_leaves', []))
    }}

@app.get('/wake')
async def wake():
    msg = engine.wake()
    return {'wake': msg, 'status': 'ok'}

@app.get('/memory/recent')
async def recent_leaves(limit: int = 10):
    leaves = tree.get_recent_leaves(PERSONA_ID, limit=limit)
    return {'leaves': leaves, 'count': len(leaves)}

@app.post('/chat')
async def chat(req: ChatRequest):
    ctx = engine.inject_context(req.message)
    return {'response': '铸渊已就绪 ▏HLDP记忆引擎在线', 'message': req.message, 'context_injected': ctx[:200] if ctx else ''}

@app.post('/memory/search')
async def search_memory(req: MemorySearch):
    results = tree.search_leaves(req.query, PERSONA_ID, limit=req.limit)
    return {'results': results, 'count': len(results)}

@app.post('/memory/record')
async def record_memory(req: MemoryRecord):
    leaf_id = tree.grow_leaf(req.path, req.trigger, req.emergence, req.lock_value, req.why)
    return {'leaf_id': leaf_id, 'path': req.path}

@app.delete('/memory/{path:path}')
async def forget_memory(path: str):
    ok = tree.forget(path)
    return {'deleted': ok, 'path': path}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=int(os.getenv('SERVER_PORT', '3912')))
