"""
Modelo ORM para la relación entre partes y países - Anexo 24
"""

from datetime import datetime
from typing import TYPE_CHECKING, Optional
from decimal import Decimal
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base
from sqlalchemy import (
    Integer,
    PrimaryKeyConstraint,
    String,
    Boolean,
    ForeignKeyConstraint,
    DateTime,
    Numeric,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

if TYPE_CHECKING:
    from api.v1.modules.a76.parts.models import Part


class PartCountry(Base, TenantScopedMixin, TimestampMixin):
    """
    Tabla inv_parte_paises: Relación entre partes y países.
    Almacena información de países de origen, preferencias, certificados y omisiones.
    """
    __tablename__ = "inv_parte_paises"
    __table_args__ = (
        PrimaryKeyConstraint("id", name="inv_parte_paises_pkey"),
        ForeignKeyConstraint(
            ["part_id"], ["a76.parts.id"], name="fk_inv_parte_paises_part"
        ),
        {"schema": "a24", "extend_existing": True},
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    part_id: Mapped[int] = mapped_column(Integer, nullable=False)
    country_code: Mapped[str] = mapped_column(String(3), nullable=False)
    
    # Información de fracciones
    fraction: Mapped[Optional[str]] = mapped_column(String(20))
    is_origin: Mapped[bool] = mapped_column(Boolean, default=False)
    
    # Preferencia comercial
    preference: Mapped[str] = mapped_column(String(15), default="GENERAL")  # GENERAL, PROSEC, ALADI, TLCS
    
    # Certificado de origen
    has_certificate: Mapped[bool] = mapped_column(Boolean, default=False)
    certificate_number: Mapped[Optional[str]] = mapped_column(String(50))
    end_date: Mapped[Optional[datetime]] = mapped_column(DateTime)
    
    # Fracciones anteriores a 7 meses
    previous_fractions_7m: Mapped[bool] = mapped_column(Boolean, default=False)
    
    # Omisiones (importación/exportación)
    omission_import: Mapped[bool] = mapped_column(Boolean, default=False)
    omission_export: Mapped[bool] = mapped_column(Boolean, default=False)
    
    # Porcentajes
    import_percentage: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 2))
    export_percentage: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 2))
    
    # Sector (para referencia)
    sector: Mapped[Optional[str]] = mapped_column(String(10))

    # Relación
    part: Mapped["Part"] = relationship("Part", back_populates="inv_countries")

    def __repr__(self) -> str:
        return f"<PartCountry(id={self.id}, part={self.part_id}, country='{self.country_code}', preference='{self.preference}')>"
