# main.py

from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from typing import List
from pydantic import BaseModel, model_validator
import uvicorn

from Temp_Diag import MSET_Temp  

app = FastAPI(title="Temperature Diagnosis API")


class TemperatureInput(BaseModel):
    windCode: str
    windTurbineNumberList: List[str]
    startTime: str  # e.g. "2024-06-08 00:00"
    endTime: str    # e.g. "2024-06-08 01:00"

    @model_validator(mode='before')
    def normalize_fields(cls, values):
        # 确保 windTurbineNumberList 是列表
        raw = values.get('windTurbineNumberList')
        if isinstance(raw, str):
            values['windTurbineNumberList'] = [raw]
        return values

class TemperatureThresholdInput(TemperatureInput):
    pageNo:   int  # 必填
    pageSize: int  # 必填

# 阈值分析
@app.post("/temperature/threshold")
async def route_threshold(input_data: TemperatureThresholdInput):
    """
    阈值分析接口（带分页）  
    - 输入：
      {
        "windCode": "WOF01000010",
        "windTurbineNumberList": ["WOG00542"],
        "startTime": "2023-01-01 00:00",
        "endTime": "2023-01-05 12:00",
        "pageNo": 2,
        "pageSize": 20
      }

    - 返回：
      {
        "data": {
          "type": "temperature_threshold",
          "records": [
            {
              "time_stamp": "2024-06-08 00:05:00",
              "temp_channel": "主轴承温度",
              "SPRT_score": 0.123,
              "status": "正常"
            },
            ...
          ]
        },
        "code": 200,
        "message": "success"
      }
    """
    try:
        analyzer = MSET_Temp(
            windCode=input_data.windCode,
            windTurbineNumberList=input_data.windTurbineNumberList,
            startTime=input_data.startTime,
            endTime=input_data.endTime
        )
        records = analyzer.check_threshold().to_dict(orient="records")

        start = (input_data.pageNo - 1) * input_data.pageSize
        end   = start + input_data.pageSize
        paginated = records[start:end]

        return {
            "data": {
                "type": "temperature_threshold",
                "records": paginated
            },
            "code": 200,
            "message": "success"
        }
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "code": 500,
                "message": "analysis failed",
                "detail": str(e)
            }
        )

# SPRT趋势分析
@app.post("/SPRT/trend")
async def route_trend(input_data: TemperatureInput):
    """
    趋势分析接口：
      - 输入:
        {
          "windCode": "WOF01000010",
          "windTurbineNumberList": ["WOG00542"],
          "startTime": "2023-01-01 00:00",
          "endTime": "2023-01-05 12:00"
        }
      - 返回：
        {
          "data": {
            "type": "SPRT_trend",
            "main_bearing": {"timestamps": [...], "values": [...]}, # 主轴承温度
            "gearbox_oil": {"timestamps": [...], "values": [...]}, # 齿轮箱油温
            "generator_drive_end": {"timestamps": [...], "values": [...]}, # 发电机驱动端轴承温度
            "generator_nondrive_end": {"timestamps": [...], "values": [...]} # 发电机非驱动端轴承温度
          },
          "code": 200,
          "message": "success"
        }
    """
    try:
        analyzer = MSET_Temp(
            windCode=input_data.windCode,
            windTurbineNumberList=input_data.windTurbineNumberList,
            startTime=input_data.startTime,
            endTime=input_data.endTime
        )
        # get_trend() 已经返回形如 {"data": { … 四个 key … }} 的字典
        result = analyzer.get_trend()

        # 组装最终响应
        return {
            "data": {
                "type": "SPRT_trend",
                **result.get("data", {})    # 四个通道的数据或空对象
            },
            "code": 200,
            "message": "success"
        }
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "code": 500,
                "message": "analysis failed",
                "detail": str(e)
            }
        )


# # 温度趋势分析（暂未调用）
# @app.post("/temperature/trend")
# async def route_trend(input_data: TemperatureInput):
#     """
#     趋势分析接口：
#       - 输入：
#         {
#           "windCode": "WOF01000010",
#           "windTurbineNumberList": ["WOG00542"],
#           "startTime": "2023-01-01 00:00",
#           "endTime": "2023-01-05 12:00"
#         }
#       - 返回：
#         {
#           "data": {
#             "type": "temperature_trend",
#             "timestamps": [ "2024-06-08 00:00:00", ... ],
#             "channels": [
#                { "temp_channel": "main_bearing_temperature", "values": [24.5, 24.7, ...] },
#                ...
#             ],
#             "unit": "°C"
#           },
#           "code": 200,
#           "message": "success"
#         }
#     """
#     try:
#         analyzer = MSET_Temp(
#             windCode=input_data.windCode,
#             windTurbineNumberList=input_data.windTurbineNumberList,
#             startTime=input_data.startTime,
#             endTime=input_data.endTime
#         )
#         result = analyzer.get_trend()
#         return {
#             "data": {
#                 "type": "temperature_trend",
#                 **result
#             },
#             "code": 200,
#             "message": "success"
#         }
#     except Exception as e:
#         return JSONResponse(
#             status_code=500,
#             content={
#                 "code": 500,
#                 "message": "analysis failed",
#                 "detail": str(e)
#             }
#         )



if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )
