"""
工作手机SDK v3.0 - 经验库API
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from services.experience_db import experience_db
from services.adb_device import adb_manager

router = APIRouter(prefix="/api/v3/experience", tags=["经验库"])


# ========== 请求模型 ==========

class ShortcutCreate(BaseModel):
    name: str
    description: str
    steps: List[Dict[str, Any]]


class ShortcutExecute(BaseModel):
    variables: Optional[Dict[str, str]] = None


class RecordOperation(BaseModel):
    device_id: str
    app: str
    action: str
    params: Dict[str, Any]
    result: Dict[str, Any]
    duration_ms: int


# ========== 统计和记录 ==========

@router.get("/statistics")
async def get_statistics():
    """获取经验库统计信息"""
    return {
        "code": 200,
        "data": experience_db.get_statistics()
    }


@router.get("/operations")
async def get_operations(limit: int = 100):
    """获取最近的操作记录"""
    return {
        "code": 200,
        "data": experience_db.get_recent_operations(limit)
    }


@router.post("/operations/record")
async def record_operation(req: RecordOperation):
    """记录一次操作"""
    op_id = experience_db.record_operation(
        device_id=req.device_id,
        app=req.app,
        action=req.action,
        params=req.params,
        result=req.result,
        duration_ms=req.duration_ms
    )
    return {
        "code": 200,
        "data": {"operation_id": op_id}
    }


# ========== 快捷操作 ==========

@router.get("/shortcuts")
async def list_shortcuts():
    """列出所有快捷操作"""
    return {
        "code": 200,
        "data": experience_db.list_shortcuts()
    }


@router.get("/shortcuts/{name}")
async def get_shortcut(name: str):
    """获取快捷操作详情"""
    shortcut = experience_db.get_shortcut(name)
    if not shortcut:
        raise HTTPException(status_code=404, detail="快捷操作不存在")
    return {
        "code": 200,
        "data": shortcut
    }


@router.post("/shortcuts")
async def create_shortcut(req: ShortcutCreate):
    """创建快捷操作"""
    shortcut = experience_db.create_shortcut(
        name=req.name,
        description=req.description,
        steps=req.steps
    )
    return {
        "code": 200,
        "data": shortcut
    }


@router.post("/shortcuts/{name}/execute/{device_id}")
async def execute_shortcut(name: str, device_id: str, req: ShortcutExecute = None):
    """
    执行快捷操作
    
    示例: 执行微信发消息
    POST /api/v3/experience/shortcuts/wechat_send_message/execute/emulator-5554
    {
        "variables": {
            "contact": "张三",
            "message": "你好"
        }
    }
    """
    device = adb_manager.get_device(device_id)
    if not device:
        raise HTTPException(status_code=404, detail="设备不存在")
    
    variables = req.variables if req else None
    result = experience_db.execute_shortcut(name, device, variables)
    
    return {
        "code": 200 if result["success"] else 500,
        "data": result
    }


# ========== 智能建议 ==========

@router.get("/suggest/coordinates")
async def suggest_coordinates(app: str, text: str):
    """
    获取坐标建议
    
    根据历史操作记录，建议某个APP中某个文字元素的坐标
    """
    suggestion = experience_db.suggest_coordinates(app, text)
    if suggestion:
        return {
            "code": 200,
            "data": suggestion
        }
    return {
        "code": 404,
        "message": "没有找到相关记录"
    }


@router.get("/success-rate")
async def get_success_rate(app: str, action: str):
    """获取某操作的成功率"""
    rate = experience_db.get_success_rate(app, action)
    return {
        "code": 200,
        "data": {
            "app": app,
            "action": action,
            "success_rate": rate
        }
    }


@router.get("/average-duration")
async def get_average_duration(app: str, action: str):
    """获取某操作的平均耗时"""
    duration = experience_db.get_average_duration(app, action)
    return {
        "code": 200,
        "data": {
            "app": app,
            "action": action,
            "average_duration_ms": duration
        }
    }


# ========== 学习到的APP元素 ==========

@router.get("/elements")
async def get_learned_elements():
    """获取学习到的APP元素"""
    return {
        "code": 200,
        "data": experience_db.app_elements
    }


@router.get("/elements/{app}")
async def get_app_elements(app: str):
    """获取某APP学习到的元素"""
    elements = experience_db.app_elements.get(app, {})
    return {
        "code": 200,
        "data": elements
    }
