"""LeAudit 文档主模型 —— leaudit_documents 表。

当前平台把它作为 LeAudit 自己的文档主表使用，不再依赖旧系统文档表。
``biz_document_id`` 字段仅保留为内部追踪号，避免直接改库。
"""

from __future__ import annotations

from sqlalchemy import BigInteger, Boolean, Integer, String
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column

from fastapi_common.fastapi_common_web.models import BaseModel


class LeauditDocument(BaseModel):
    """LeAudit 平台内部文档主表。"""

    __tablename__ = "leaudit_documents"

    Id: Mapped[int] = mapped_column("id", BigInteger, primary_key=True, autoincrement=True)
    bizDocumentId: Mapped[int] = mapped_column("biz_document_id", BigInteger, unique=True, comment="内部追踪号（兼容旧字段名）")
    typeId: Mapped[int | None] = mapped_column("type_id", BigInteger, comment="文档类型ID")
    groupId: Mapped[int | None] = mapped_column("group_id", BigInteger, comment="命中的二级分组ID")
    processingStatus: Mapped[str | None] = mapped_column("processing_status", String(64), default="waiting", comment="waiting/processing/completed/failed")
    currentRunId: Mapped[int | None] = mapped_column("current_run_id", BigInteger, comment="最新有效 run id")
    region: Mapped[str] = mapped_column(String(32), default="default", comment="所属地区: mz/yf/jy/cz/default")
    versionGroupKey: Mapped[str | None] = mapped_column("version_group_key", String(64), comment="文档版本归档组键")
    versionNo: Mapped[int] = mapped_column("version_no", Integer, default=1, comment="同一文档系列中的版本号")
    previousVersionId: Mapped[int | None] = mapped_column("previous_version_id", BigInteger, comment="上一版本文档ID")
    rootVersionId: Mapped[int | None] = mapped_column("root_version_id", BigInteger, comment="首版本文档ID")
    isLatestVersion: Mapped[bool] = mapped_column("is_latest_version", Boolean, default=True, comment="是否当前最新版本")
    normalizedName: Mapped[str | None] = mapped_column("normalized_name", String(512), comment="归一化文件名（不含扩展名）")

    @classmethod
    async def create_new(cls, session: AsyncSession, **fields) -> "LeauditDocument":
        """Create a new platform-side document row for every upload."""
        doc = cls(**fields)
        session.add(doc)
        await session.flush()
        return doc
