"""
Linux BenchTools - Peripheral Models
"""

from sqlalchemy import Column, Integer, String, Float, Boolean, Date, DateTime, Text, JSON
from sqlalchemy.sql import func
from app.db.base import BasePeripherals


class Peripheral(BasePeripherals):
    """
    Peripheral model - Main table for all peripherals
    """
    __tablename__ = "peripherals"

    # ========================================
    # IDENTIFICATION
    # ========================================
    id = Column(Integer, primary_key=True, index=True)
    nom = Column(String(255), nullable=False, index=True)
    type_principal = Column(String(100), nullable=False, index=True)
    sous_type = Column(String(100), index=True)
    marque = Column(String(100), index=True)
    modele = Column(String(255))
    fabricant = Column(String(255))  # iManufacturer (USB manufacturer string)
    produit = Column(String(255))  # iProduct (USB product string)
    numero_serie = Column(String(255))
    ean_upc = Column(String(50))

    # ========================================
    # ACHAT
    # ========================================
    boutique = Column(String(255))
    date_achat = Column(Date)
    prix = Column(Float)
    devise = Column(String(10), default="EUR")
    garantie_duree_mois = Column(Integer)
    garantie_expiration = Column(Date)

    # ========================================
    # ÉVALUATION
    # ========================================
    rating = Column(Float, default=0.0)  # 0-5 étoiles

    # ========================================
    # STOCK
    # ========================================
    quantite_totale = Column(Integer, default=1)
    quantite_disponible = Column(Integer, default=1)
    seuil_alerte = Column(Integer, default=0)

    # ========================================
    # MÉTADONNÉES
    # ========================================
    date_creation = Column(DateTime, server_default=func.now())
    date_modification = Column(DateTime, onupdate=func.now())
    etat = Column(String(50), default="Neuf", index=True)  # Neuf, Bon, Usagé, Défectueux, Retiré
    localisation = Column(String(255))
    proprietaire = Column(String(100))
    tags = Column(Text)  # JSON array
    notes = Column(Text)

    # ========================================
    # LINUX IDENTIFICATION
    # ========================================
    device_path = Column(String(255))
    sysfs_path = Column(String(500))
    vendor_id = Column(String(20))
    product_id = Column(String(20))
    usb_device_id = Column(String(20))  # idVendor:idProduct (e.g. 1d6b:0003)
    iManufacturer = Column(Text)  # USB manufacturer string from lsusb
    iProduct = Column(Text)  # USB product string from lsusb
    class_id = Column(String(20))
    driver_utilise = Column(String(100))
    modules_kernel = Column(Text)  # JSON
    udev_rules = Column(Text)
    identifiant_systeme = Column(Text)

    # ========================================
    # INSTALLATION
    # ========================================
    installation_auto = Column(Boolean, default=False)
    driver_requis = Column(Text)
    firmware_requis = Column(Text)
    paquets_necessaires = Column(Text)  # JSON
    commandes_installation = Column(Text)
    problemes_connus = Column(Text)
    solutions = Column(Text)
    compatibilite_noyau = Column(String(100))

    # ========================================
    # CONNECTIVITÉ
    # ========================================
    interface_connexion = Column(String(100))
    connecte_a = Column(String(255))
    consommation_electrique_w = Column(Float)

    # ========================================
    # LOCALISATION PHYSIQUE
    # ========================================
    location_id = Column(Integer)  # FK vers locations
    location_details = Column(String(500))
    location_auto = Column(Boolean, default=True)

    # ========================================
    # PRÊT
    # ========================================
    en_pret = Column(Boolean, default=False, index=True)
    pret_actuel_id = Column(Integer)  # FK vers peripheral_loans
    prete_a = Column(String(255))

    # ========================================
    # APPAREIL COMPLET
    # ========================================
    is_complete_device = Column(Boolean, default=False, index=True)
    device_type = Column(String(50))  # desktop, laptop, tablet, smartphone, server, console

    # ========================================
    # LIEN VERS DB PRINCIPALE (logique, pas FK SQL)
    # ========================================
    linked_device_id = Column(Integer, index=True)  # → devices.id dans data.db (benchmarks)
    device_id = Column(Integer, index=True)  # → devices.id dans data.db (assignation actuelle)

    # ========================================
    # DOCUMENTATION
    # ========================================
    description = Column(Text)  # Description courte du périphérique
    synthese = Column(Text)  # Synthèse complète du fichier markdown importé
    cli = Column(Text)  # DEPRECATED: Sortie CLI (lsusb -v) - use cli_yaml + cli_raw instead
    cli_yaml = Column(Text)  # Données structurées CLI au format YAML
    cli_raw = Column(Text)  # Sortie CLI brute (lsusb -v, lshw, etc.) au format Markdown
    specifications = Column(Text)  # Spécifications techniques (format Markdown) - contenu brut importé depuis .md
    notes = Column(Text)  # Notes libres (format Markdown)

    # ========================================
    # DONNÉES SPÉCIFIQUES
    # ========================================
    caracteristiques_specifiques = Column(JSON)  # Flexible JSON par type

    def __repr__(self):
        return f"<Peripheral(id={self.id}, nom='{self.nom}', type='{self.type_principal}')>"


class PeripheralPhoto(BasePeripherals):
    """Photos of peripherals"""
    __tablename__ = "peripheral_photos"

    id = Column(Integer, primary_key=True)
    peripheral_id = Column(Integer, nullable=False, index=True)
    filename = Column(String(255), nullable=False)
    stored_path = Column(String(500), nullable=False)
    thumbnail_path = Column(String(500))  # Path to thumbnail image
    mime_type = Column(String(100))
    size_bytes = Column(Integer)
    uploaded_at = Column(DateTime, server_default=func.now())
    description = Column(Text)
    is_primary = Column(Boolean, default=False)

    def __repr__(self):
        return f"<PeripheralPhoto(id={self.id}, peripheral_id={self.peripheral_id})>"


class PeripheralDocument(BasePeripherals):
    """Documents attached to peripherals (manuals, warranties, invoices, etc.)"""
    __tablename__ = "peripheral_documents"

    id = Column(Integer, primary_key=True)
    peripheral_id = Column(Integer, nullable=False, index=True)
    doc_type = Column(String(50), nullable=False, index=True)  # manual, warranty, invoice, datasheet, other
    filename = Column(String(255), nullable=False)
    stored_path = Column(String(500), nullable=False)
    mime_type = Column(String(100))
    size_bytes = Column(Integer)
    uploaded_at = Column(DateTime, server_default=func.now())
    description = Column(Text)

    def __repr__(self):
        return f"<PeripheralDocument(id={self.id}, type='{self.doc_type}')>"


class PeripheralLink(BasePeripherals):
    """Links related to peripherals (manufacturer, support, drivers, etc.)"""
    __tablename__ = "peripheral_links"

    id = Column(Integer, primary_key=True)
    peripheral_id = Column(Integer, nullable=False, index=True)
    link_type = Column(String(50), nullable=False)  # manufacturer, support, drivers, documentation, custom
    label = Column(String(255), nullable=False)
    url = Column(Text, nullable=False)

    def __repr__(self):
        return f"<PeripheralLink(id={self.id}, label='{self.label}')>"


class PeripheralLoan(BasePeripherals):
    """Loan/borrow tracking for peripherals"""
    __tablename__ = "peripheral_loans"

    id = Column(Integer, primary_key=True)
    peripheral_id = Column(Integer, nullable=False, index=True)

    # Emprunteur
    emprunte_par = Column(String(255), nullable=False, index=True)
    email_emprunteur = Column(String(255))
    telephone = Column(String(50))

    # Dates
    date_pret = Column(Date, nullable=False)
    date_retour_prevue = Column(Date, nullable=False, index=True)
    date_retour_effectif = Column(Date)

    # Statut
    statut = Column(String(50), nullable=False, default="en_cours", index=True)  # en_cours, retourne, en_retard

    # Caution
    caution_montant = Column(Float)
    caution_rendue = Column(Boolean, default=False)

    # État
    etat_depart = Column(String(50))
    etat_retour = Column(String(50))
    problemes_retour = Column(Text)

    # Informations
    raison_pret = Column(Text)
    notes = Column(Text)
    created_by = Column(String(100))

    # Rappels
    rappel_envoye = Column(Boolean, default=False)
    date_rappel = Column(DateTime)

    def __repr__(self):
        return f"<PeripheralLoan(id={self.id}, emprunte_par='{self.emprunte_par}', statut='{self.statut}')>"
