from sqlalchemy import JSON, Column, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

from mineru_flow.internal.common.db import Base
from mineru_flow.internal.schema.state import JobStatus, Phase, State


class Task(Base):
    """任务模型"""

    __tablename__ = "tasks"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(255), nullable=False, comment="任务名称")
    created_at = Column(
        DateTime, default=func.now(), nullable=False, comment="创建时间"
    )
    updated_at = Column(DateTime, onupdate=func.now(), comment="更新时间")
    job_id = Column(
        Integer, ForeignKey("jobs.id"), nullable=False, comment="关联的作业ID"
    )

    # 关联关系
    job = relationship("Job", back_populates="task", uselist=False)

    state = Column(String(50), default=State.ENABLED, nullable=False, comment="状态")


class Job(Base):
    """作业模型"""

    __tablename__ = "jobs"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    error_message = Column(Text, comment="错误信息")
    phases = Column(JSON, comment="处理阶段列表")
    phase = Column(String(50), default=Phase.PARSE, nullable=False, comment="当前阶段")
    status = Column(
        String(50), default=JobStatus.WAITING, nullable=False, comment="状态"
    )
    created_at = Column(
        DateTime, default=func.now(), nullable=False, comment="创建时间"
    )
    updated_at = Column(DateTime, onupdate=func.now(), comment="更新时间")
    config = Column(JSON, comment="作业配置")
    results = Column(MutableDict.as_mutable(JSON), comment="作业结果")

    # 关联关系
    task = relationship("Task", back_populates="job", uselist=False)

    state = Column(String(50), default=State.ENABLED, nullable=False, comment="状态")


class Config(Base):
    """配置模型"""

    __tablename__ = "configs"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    type = Column(String(50), nullable=False, comment="配置类型")
    name = Column(String(255), nullable=False, comment="配置名称")
    value = Column(JSON, comment="配置值")
    created_at = Column(
        DateTime, default=func.now(), nullable=False, comment="创建时间"
    )
    state = Column(String(50), default=State.ENABLED, nullable=False, comment="状态")
