from sqlalchemy import Column, Integer, String, JSON, UniqueConstraint, text, Boolean, DateTime, ForeignKey, Numeric, Index, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import JSONB  # PostgreSQL specifikus JSONB a hatékony kereséshez
from app.db.base_class import Base

class VehicleType(Base):
    """Jármű főtípusok sémája (Séma-gazda)"""
    __tablename__ = "vehicle_types"
    __table_args__ = {"schema": "data"}

    id = Column(Integer, primary_key=True)
    code = Column(String(30), unique=True, index=True) # car, motorcycle, truck, bus, boat, etc.
    name = Column(String(50)) # Megjelenítendő név
    icon = Column(String(50))
    units = Column(JSON, server_default=text("'{\"power\": \"kW\", \"weight\": \"kg\", \"cargo\": \"m3\"}'::jsonb"))

    features = relationship("FeatureDefinition", back_populates="vehicle_type")
    definitions = relationship("VehicleModelDefinition", back_populates="v_type_rel")

class FeatureDefinition(Base):
    """Globális felszereltség szótár"""
    __tablename__ = "feature_definitions"
    __table_args__ = {"schema": "data"}

    id = Column(Integer, primary_key=True)
    vehicle_type_id = Column(Integer, ForeignKey("data.vehicle_types.id"))
    category = Column(String(50)) # Műszaki, Beltér, Kültér, Multimédia
    name = Column(String(100), nullable=False)
    data_type = Column(String(20), default="boolean")

    vehicle_type = relationship("VehicleType", back_populates="features")

class ModelFeatureMap(Base):
    """Modell-szintű felszereltségi sablon (Alap vs Extra)"""
    __tablename__ = "model_feature_maps"
    __table_args__ = {"schema": "data"}

    model_id = Column(Integer, ForeignKey("data.vehicle_model_definitions.id"), primary_key=True)
    feature_id = Column(Integer, ForeignKey("data.feature_definitions.id"), primary_key=True)
    availability = Column(String(20), default="standard") # standard, optional, accessory
    value = Column(String(100))

class VehicleModelDefinition(Base):
    """MDM Master rekordok - v1.3.0 Pipeline Edition (Researcher & Alchemist)"""
    __tablename__ = "vehicle_model_definitions"
    __table_args__ = (
        UniqueConstraint('make', 'technical_code', 'vehicle_type', name='uix_make_tech_type'),
        Index('idx_vmd_lookup', 'make', 'technical_code'),
        {"schema": "data"}
    )

    id = Column(Integer, primary_key=True)
    make = Column(String(50), nullable=False, index=True)
    technical_code = Column(String(50), nullable=False, index=True)
    marketing_name = Column(String(100), index=True)
    family_name = Column(String(100))
    
    vehicle_type = Column(String(30), index=True) 
    vehicle_type_id = Column(Integer, ForeignKey("data.vehicle_types.id"))
    vehicle_class = Column(String(50))
    
    parent_id = Column(Integer, ForeignKey("data.vehicle_model_definitions.id"), nullable=True)
    year_from = Column(Integer, nullable=True, index=True)
    year_to = Column(Integer, nullable=True, index=True)
    synonyms = Column(JSON, server_default=text("'[]'::jsonb"))

    # --- ROBOT VÉDELMI ÉS PIPELINE MEZŐK (v1.3.0) ---
    is_manual = Column(Boolean, default=False, server_default=text("false"), index=True)
    attempts = Column(Integer, default=0, server_default=text("0"), index=True)
    last_error = Column(Text, nullable=True)

    # Robot 2.1 "Researcher" porszívózott nyers adatai (A szemetesláda)
    raw_search_context = Column(Text, nullable=True)
    
    # Telemetria és forrás adatok (melyik API/URL hozta az adatot)
    research_metadata = Column(JSONB, server_default=text("'{}'::jsonb"), nullable=False)
    # --------------------------------------------------

    # --- TECHNIKAI FIX OSZLOPOK ---
    engine_capacity = Column(Integer, index=True)
    power_kw = Column(Integer, index=True)
    max_weight_kg = Column(Integer, index=True)
    
    axle_count = Column(Integer)
    payload_capacity_kg = Column(Integer)
    cargo_volume_m3 = Column(Numeric(10, 2))
    cargo_length_mm = Column(Integer)
    cargo_width_mm = Column(Integer)
    cargo_height_mm = Column(Integer)

    specifications = Column(JSON, server_default=text("'{}'::jsonb"))
    features_json = Column(JSON, server_default=text("'{}'::jsonb"))
    
    # Státusz mező hossza növelve a pipeline flagekhez
    status = Column(String(30), server_default="unverified", index=True) 
    is_master = Column(Boolean, default=False)
    source = Column(String(50)) # 'ROBOT-v1.3.0-Pipeline'
    
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # Kapcsolatok
    v_type_rel = relationship("VehicleType", back_populates="definitions")
    master_record = relationship("VehicleModelDefinition", remote_side=[id], backref="merged_variants")
    
    # AssetCatalog kapcsolat
    # Megjegyzés: Ellenőrizd, hogy az AssetCatalog modell be van-e importálva a Base-be!
    variants = relationship("AssetCatalog", back_populates="master_definition", primaryjoin="VehicleModelDefinition.id == AssetCatalog.master_definition_id")