from __future__ import annotations

from datetime import datetime

from sqlalchemy import BigInteger, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import Base

PRIMARY_KEY_TYPE = BigInteger().with_variant(Integer, "sqlite")


class TopicSummary(Base):
    __tablename__ = "sys_topic_summary"
    __table_args__ = (
        UniqueConstraint("topic_session_id", name="uq_sys_topic_summary_topic"),
        Index("ix_topic_summary_job_due", "status", "next_run_at", "id"),
        Index("ix_topic_summary_job_stale", "status", "locked_at"),
    )

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    topic_session_id: Mapped[int] = mapped_column(ForeignKey("sys_topic_session.id"), index=True, nullable=False)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    schema_version: Mapped[int] = mapped_column(Integer, default=2, nullable=False)
    summary: Mapped[str] = mapped_column(Text, nullable=False)
    main_events: Mapped[str | None] = mapped_column(Text, nullable=True)
    emotions: Mapped[str | None] = mapped_column(Text, nullable=True)
    body_feelings: Mapped[str | None] = mapped_column(Text, nullable=True)
    beliefs: Mapped[str | None] = mapped_column(Text, nullable=True)
    recommended_homework: Mapped[str | None] = mapped_column(Text, nullable=True)
    insights: Mapped[str | None] = mapped_column(Text, nullable=True)
    next_observation: Mapped[str | None] = mapped_column(Text, nullable=True)
    model_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    status: Mapped[str] = mapped_column(String(20), default="success", index=True, nullable=False)
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    attempt_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    max_attempts: Mapped[int] = mapped_column(Integer, default=3, nullable=False)
    next_run_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    locked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    locked_by: Mapped[str | None] = mapped_column(String(120), nullable=True)
    last_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    generated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)
    updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)


class UserGrowthProfile(Base):
    __tablename__ = "sys_user_growth_profile"
    __table_args__ = (UniqueConstraint("user_id", name="uq_sys_user_growth_profile_user"),)

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    schema_version: Mapped[int] = mapped_column(Integer, default=2, nullable=False)
    recent_review: Mapped[str | None] = mapped_column(Text, nullable=True)
    current_focus: Mapped[str | None] = mapped_column(Text, nullable=True)
    source_summary_ids: Mapped[str | None] = mapped_column(Text, nullable=True)
    # 以下字段仅为兼容历史数据保留。V2 近期实修回顾不再生成、展示或注入这些画像字段。
    profile_text: Mapped[str] = mapped_column(Text, default="", nullable=False)
    recurring_topics: Mapped[str | None] = mapped_column(Text, nullable=True)
    common_emotions: Mapped[str | None] = mapped_column(Text, nullable=True)
    body_patterns: Mapped[str | None] = mapped_column(Text, nullable=True)
    relation_patterns: Mapped[str | None] = mapped_column(Text, nullable=True)
    homework_done: Mapped[str | None] = mapped_column(Text, nullable=True)
    effective_homework: Mapped[str | None] = mapped_column(Text, nullable=True)
    recent_progress: Mapped[str | None] = mapped_column(Text, nullable=True)
    last_topic_summary_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
    updated_by: Mapped[str] = mapped_column(String(30), default="system", nullable=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)
    updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)


class GrowthProfileRevision(Base):
    __tablename__ = "sys_growth_profile_revision"

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    profile_id: Mapped[int] = mapped_column(ForeignKey("sys_user_growth_profile.id"), index=True, nullable=False)
    topic_summary_id: Mapped[int | None] = mapped_column(BigInteger, index=True, nullable=True)
    before_json: Mapped[str | None] = mapped_column(Text, nullable=True)
    after_json: Mapped[str] = mapped_column(Text, nullable=False)
    reason: Mapped[str] = mapped_column(String(50), default="topic_summary", nullable=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)


class TeacherHelpCard(Base):
    __tablename__ = "sys_teacher_help_card"
    __table_args__ = (
        Index("ix_sys_teacher_help_card_user_created", "user_id", "created_at"),
        Index("ix_sys_teacher_help_card_topic_created", "topic_session_id", "created_at"),
    )

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    topic_session_id: Mapped[int] = mapped_column(ForeignKey("sys_topic_session.id"), index=True, nullable=False)
    summary_id: Mapped[int | None] = mapped_column(BigInteger, index=True, nullable=True)
    content: Mapped[str] = mapped_column(Text, nullable=False)
    source: Mapped[str] = mapped_column(String(30), default="topic_summary", nullable=False)
    copied: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    copied_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)


class ShareDraft(Base):
    __tablename__ = "sys_share_draft"
    __table_args__ = (
        Index("ix_sys_share_draft_user_created", "user_id", "created_at"),
        Index("ix_sys_share_draft_topic_created", "topic_session_id", "created_at"),
    )

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    topic_session_id: Mapped[int] = mapped_column(ForeignKey("sys_topic_session.id"), index=True, nullable=False)
    summary_id: Mapped[int | None] = mapped_column(BigInteger, index=True, nullable=True)
    content: Mapped[str] = mapped_column(Text, nullable=False)
    source: Mapped[str] = mapped_column(String(30), default="topic_summary", nullable=False)
    copied: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    copied_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)


class PeriodicReport(Base):
    __tablename__ = "sys_periodic_report"
    __table_args__ = (
        UniqueConstraint("user_id", "report_type", "period_start", "period_end", name="uq_sys_periodic_report_period"),
        Index("ix_sys_periodic_report_user_type_created", "user_id", "report_type", "created_at"),
        Index("ix_sys_periodic_report_status_created", "status", "created_at"),
        Index("ix_periodic_report_job_due", "status", "next_run_at", "id"),
        Index("ix_periodic_report_job_stale", "status", "locked_at"),
    )

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    schema_version: Mapped[int] = mapped_column(Integer, default=2, nullable=False)
    report_type: Mapped[str] = mapped_column(String(30), nullable=False)
    period_start: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    period_end: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    title: Mapped[str] = mapped_column(String(160), nullable=False)
    content: Mapped[str] = mapped_column(Text, default="", nullable=False)
    source_summary_ids: Mapped[str | None] = mapped_column(Text, nullable=True)
    source_topic_ids: Mapped[str | None] = mapped_column(Text, nullable=True)
    model_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    status: Mapped[str] = mapped_column(String(20), default="success", index=True, nullable=False)
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    generated_by: Mapped[str] = mapped_column(String(30), default="manual", nullable=False)
    attempt_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    max_attempts: Mapped[int] = mapped_column(Integer, default=3, nullable=False)
    next_run_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    locked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    locked_by: Mapped[str | None] = mapped_column(String(120), nullable=True)
    last_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    generated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)
    updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
