from sqlalchemy import BIGINT, FLOAT, TIMESTAMP, Enum, Index, Integer, JSON, String, Text, text
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class MonitorExperiment(Base):
    __tablename__ = 'monitor_experiments'
    __table_args__ = (
        Index('idx_exp_status', 'status'),
        {'mysql_comment': '实时控制试验表'},
    )

    id: Mapped[int] = mapped_column(BIGINT, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(255), nullable=False, comment='试验名称')
    model_id: Mapped[int] = mapped_column(BIGINT, nullable=False, comment='模型ID')
    model_name: Mapped[str] = mapped_column(String(255), nullable=False, comment='模型名称')
    package_id: Mapped[int] = mapped_column(BIGINT, nullable=False, comment='初始数据包ID')
    package_name: Mapped[str] = mapped_column(String(255), nullable=False, comment='数据包名称')
    target_temp: Mapped[float] = mapped_column(FLOAT, nullable=False, comment='目标温度(°C)')
    mpc_params: Mapped[dict] = mapped_column(JSON, nullable=False, comment='MPC参数')
    status: Mapped[str] = mapped_column(
        Enum('idle', 'running', 'stopped', name='exp_status_enum'),
        nullable=False,
        server_default=text("'idle'"),
        comment='试验状态: idle/running/stopped',
    )
    total_steps: Mapped[int] = mapped_column(
        Integer, nullable=False, server_default=text('0'), comment='已采集步数'
    )
    start_time: Mapped[str | None] = mapped_column(TIMESTAMP, nullable=True, comment='开始时间')
    stop_time: Mapped[str | None] = mapped_column(TIMESTAMP, nullable=True, comment='停止时间')
    error_msg: Mapped[str | None] = mapped_column(Text, nullable=True, comment='错误信息')
    sampling_interval: Mapped[float] = mapped_column(
        FLOAT, nullable=False, server_default=text('1.0'), comment='采样周期(秒)'
    )
    exported: Mapped[int] = mapped_column(
        Integer, nullable=False, server_default=text('0'), comment='是否已导出到历史数据'
    )
    created_at: Mapped[str] = mapped_column(
        TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP')
    )


class MonitorDataPoint(Base):
    __tablename__ = 'monitor_data_points'
    __table_args__ = (
        Index('idx_dp_exp_step', 'experiment_id', 'step_idx'),
        {'mysql_comment': '试验数据点表'},
    )

    id: Mapped[int] = mapped_column(BIGINT, primary_key=True, autoincrement=True)
    experiment_id: Mapped[int] = mapped_column(BIGINT, nullable=False, comment='试验ID')
    step_idx: Mapped[int] = mapped_column(Integer, nullable=False, comment='步骤序号')
    actual_temp: Mapped[float] = mapped_column(FLOAT, nullable=False, comment='实际温度(°C)')
    reference_temp: Mapped[float] = mapped_column(FLOAT, nullable=False, comment='参考轨迹温度(°C)')
    current_output: Mapped[float] = mapped_column(FLOAT, nullable=False, comment='电流输出(A)')
    created_at: Mapped[str] = mapped_column(
        TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP')
    )
