from datetime import date, datetime

from sqlalchemy import Date, DateTime, Index, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class SecFilingGap(Base):
    """Active SEC filing that could not yet be reconstructed.

    Rows form a small retry queue. Successful snapshot ingestion deletes the
    matching row; a later valid filing supersedes it. While a current row remains,
    tickers mapped to its CIK are not eligible for actionable trade setups.
    """

    __tablename__ = "sec_filing_gaps"
    __table_args__ = (
        UniqueConstraint("accession", name="uq_sec_filing_gaps_accession"),
        Index("ix_sec_filing_gaps_cik", "cik"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    cik: Mapped[str] = mapped_column(String(10), nullable=False)
    accession: Mapped[str] = mapped_column(String(25), nullable=False)
    form: Mapped[str | None] = mapped_column(String(12), nullable=True)
    index_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    reason: Mapped[str] = mapped_column(String(64), nullable=False)
    coregistrant_ciks_json: Mapped[str | None] = mapped_column(Text, nullable=True)
    first_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    last_attempted_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    escalated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
