from __future__ import annotations

from datetime import datetime

from sqlalchemy import (
    BigInteger,
    Boolean,
    DateTime,
    Float,
    ForeignKey,
    Index,
    Integer,
    JSON,
    String,
    Text,
    UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from .database import Base
from .time_utils import utc_now_naive


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    account_uid: Mapped[str | None] = mapped_column(String(32), unique=True, index=True, nullable=True)
    email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
    name: Mapped[str] = mapped_column(String(120))
    password_hash: Mapped[str] = mapped_column(String(255))
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    is_admin: Mapped[bool] = mapped_column(Boolean, default=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, onupdate=utc_now_naive
    )

    sessions: Mapped[list["UserSession"]] = relationship(
        back_populates="user", cascade="all, delete-orphan"
    )
    preferences: Mapped[list["UserPreference"]] = relationship(
        back_populates="user", cascade="all, delete-orphan"
    )
    preference_profiles: Mapped[list["PreferenceProfile"]] = relationship(
        back_populates="user", cascade="all, delete-orphan"
    )
    projects: Mapped[list["Project"]] = relationship(
        back_populates="owner", cascade="all, delete-orphan"
    )
    calculation_jobs: Mapped[list["CalculationJob"]] = relationship(
        back_populates="user", cascade="all, delete-orphan"
    )


class AdminAuditEvent(Base):
    __tablename__ = "admin_audit_events"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    actor_user_id: Mapped[int | None] = mapped_column(
        ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
    )
    target_user_id: Mapped[int | None] = mapped_column(
        ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
    )
    action: Mapped[str] = mapped_column(String(80), index=True)
    resource: Mapped[str] = mapped_column(String(160))
    ip_address: Mapped[str | None] = mapped_column(String(64), nullable=True)
    user_agent: Mapped[str | None] = mapped_column(String(512), nullable=True)
    details_json: Mapped[dict] = mapped_column(JSON, default=dict)
    created_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, index=True
    )


class UserSession(Base):
    __tablename__ = "user_sessions"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    expires_at: Mapped[datetime] = mapped_column(DateTime, index=True)
    revoked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    ip_address: Mapped[str | None] = mapped_column(String(64), nullable=True)
    user_agent: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    last_seen_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)

    user: Mapped[User] = relationship(back_populates="sessions")


class UserPreference(Base):
    __tablename__ = "user_preferences"
    __table_args__ = (UniqueConstraint("user_id", "namespace", name="uq_user_pref_namespace"),)

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    namespace: Mapped[str] = mapped_column(String(80))
    values_json: Mapped[dict] = mapped_column(JSON, default=dict)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, onupdate=utc_now_naive
    )

    user: Mapped[User] = relationship(back_populates="preferences")


class PreferenceProfile(Base):
    __tablename__ = "preference_profiles"
    __table_args__ = (UniqueConstraint("user_id", "slug", name="uq_user_pref_profile_slug"),)

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    slug: Mapped[str] = mapped_column(String(80))
    name: Mapped[str] = mapped_column(String(120))
    values_json: Mapped[dict] = mapped_column(JSON, default=dict)
    is_default: Mapped[bool] = mapped_column(Boolean, default=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, onupdate=utc_now_naive
    )

    user: Mapped[User] = relationship(back_populates="preference_profiles")


class Project(Base):
    __tablename__ = "projects"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    project_uid: Mapped[str] = mapped_column(String(36), unique=True, index=True)
    owner_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    name: Mapped[str] = mapped_column(String(160))
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    current_version_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
    storage_bytes: Mapped[int] = mapped_column(Integer, default=0)
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, onupdate=utc_now_naive
    )

    owner: Mapped[User] = relationship(back_populates="projects")
    versions: Mapped[list["ProjectVersion"]] = relationship(
        back_populates="project", cascade="all, delete-orphan"
    )
    shares: Mapped[list["ProjectShare"]] = relationship(
        back_populates="project", cascade="all, delete-orphan"
    )


class ProjectVersion(Base):
    __tablename__ = "project_versions"
    __table_args__ = (UniqueConstraint("project_id", "version_number", name="uq_project_version"),)

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    project_id: Mapped[int] = mapped_column(ForeignKey("projects.id"), index=True)
    version_number: Mapped[int] = mapped_column(Integer)
    created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    document_json: Mapped[dict] = mapped_column(JSON, default=dict)
    document_hash: Mapped[str] = mapped_column(String(64))
    size_bytes: Mapped[int] = mapped_column(Integer, default=0)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    note: Mapped[str | None] = mapped_column(String(255), nullable=True)

    project: Mapped[Project] = relationship(back_populates="versions")


class ProjectShare(Base):
    __tablename__ = "project_shares"
    __table_args__ = (
        UniqueConstraint("project_id", "shared_with_account_uid", name="uq_project_share_account"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    project_id: Mapped[int] = mapped_column(ForeignKey("projects.id"), index=True)
    shared_with_account_uid: Mapped[str] = mapped_column(String(32), index=True)
    permission: Mapped[str] = mapped_column(String(20), default="view")
    created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    revoked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    project: Mapped[Project] = relationship(back_populates="shares")


class CalculationJob(Base):
    __tablename__ = "calculation_jobs"
    __table_args__ = (
        UniqueConstraint(
            "user_id",
            "idempotency_key_hash",
            name="uq_calculation_job_user_idempotency",
        ),
        UniqueConstraint(
            "owner_token_hash",
            "idempotency_key_hash",
            name="uq_calculation_job_guest_idempotency",
        ),
        Index(
            "ix_calculation_jobs_queue",
            "status",
            "required_class",
            "priority",
            "created_at",
        ),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    job_uid: Mapped[str] = mapped_column(String(36), unique=True, index=True)
    user_id: Mapped[int | None] = mapped_column(
        ForeignKey("users.id"), index=True, nullable=True
    )
    owner_token_hash: Mapped[str | None] = mapped_column(
        String(64), index=True, nullable=True
    )
    status: Mapped[str] = mapped_column(String(24), index=True, default="queued")
    required_class: Mapped[str] = mapped_column(String(24), index=True)
    assigned_class: Mapped[str | None] = mapped_column(String(24), nullable=True)
    priority: Mapped[int] = mapped_column(Integer, default=0)
    node_count: Mapped[int] = mapped_column(Integer)
    element_count: Mapped[int] = mapped_column(Integer)
    estimated_dof: Mapped[int] = mapped_column(Integer)
    estimated_memory_mb: Mapped[int] = mapped_column(Integer)
    request_artifact: Mapped[str] = mapped_column(String(255))
    request_sha256: Mapped[str] = mapped_column(String(64))
    request_size_bytes: Mapped[int] = mapped_column(BigInteger)
    result_artifact: Mapped[str | None] = mapped_column(String(255), nullable=True)
    result_sha256: Mapped[str | None] = mapped_column(String(64), nullable=True)
    result_size_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
    result_summary_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    idempotency_key_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
    worker_uid: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    run_token: Mapped[str | None] = mapped_column(String(36), nullable=True)
    attempt_count: Mapped[int] = mapped_column(Integer, default=0)
    max_attempts: Mapped[int] = mapped_column(Integer, default=2)
    error_code: Mapped[str | None] = mapped_column(String(40), nullable=True)
    error_message: Mapped[str | None] = mapped_column(String(1000), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, onupdate=utc_now_naive
    )
    started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    heartbeat_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    lease_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, index=True)
    cancellation_requested_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    user: Mapped[User | None] = relationship(back_populates="calculation_jobs")


class CalculationWorker(Base):
    __tablename__ = "calculation_workers"

    worker_uid: Mapped[str] = mapped_column(String(64), primary_key=True)
    hostname: Mapped[str] = mapped_column(String(255))
    process_id: Mapped[int] = mapped_column(Integer)
    pool_class: Mapped[str] = mapped_column(String(24), index=True)
    status: Mapped[str] = mapped_column(String(24), index=True, default="active")
    active_job_uid: Mapped[str | None] = mapped_column(String(36), nullable=True)
    started_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    heartbeat_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive, index=True)


class SectionProfile(Base):
    __tablename__ = "section_profiles"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    profile_key: Mapped[str] = mapped_column(String(120), unique=True, index=True)
    source_id: Mapped[str] = mapped_column(String(80), index=True)
    source_name: Mapped[str] = mapped_column(String(160))
    source_url: Mapped[str | None] = mapped_column(Text, nullable=True)
    source_revision: Mapped[str | None] = mapped_column(String(80), nullable=True)
    standard_refs: Mapped[str | None] = mapped_column(String(200), nullable=True)
    manufacturer: Mapped[str | None] = mapped_column(String(80), nullable=True)
    steel_grade: Mapped[str | None] = mapped_column(String(80), nullable=True)
    manufacturing_process: Mapped[str] = mapped_column(String(40), index=True)
    process_label: Mapped[str] = mapped_column(String(80))
    family: Mapped[str] = mapped_column(String(40), index=True)
    family_label: Mapped[str] = mapped_column(String(80))
    series: Mapped[str] = mapped_column(String(40), index=True)
    series_label: Mapped[str] = mapped_column(String(80))
    shape_type: Mapped[str] = mapped_column(String(80))
    designation: Mapped[str] = mapped_column(String(120), index=True)
    label: Mapped[str] = mapped_column(String(120))
    available_by_order: Mapped[bool] = mapped_column(Boolean, default=False)
    mass_kg_m: Mapped[float] = mapped_column(Float)
    area_m2: Mapped[float] = mapped_column(Float)
    ix_m4: Mapped[float] = mapped_column(Float)
    iy_m4: Mapped[float] = mapped_column(Float)
    j_m4: Mapped[float] = mapped_column(Float)
    d_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    bf_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    tw_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    tf_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    h_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    d_prime_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    wx_m3: Mapped[float | None] = mapped_column(Float, nullable=True)
    wy_m3: Mapped[float | None] = mapped_column(Float, nullable=True)
    rx_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    ry_m: Mapped[float | None] = mapped_column(Float, nullable=True)
    zx_m3: Mapped[float | None] = mapped_column(Float, nullable=True)
    zy_m3: Mapped[float | None] = mapped_column(Float, nullable=True)
    cw_m6: Mapped[float | None] = mapped_column(Float, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now_naive)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=utc_now_naive, onupdate=utc_now_naive
    )
