"""DataSource model — registry of external data sources for import."""

import uuid
from sqlalchemy import Column, String, Text, Boolean, DateTime, Index, func
from sqlalchemy.dialects.postgresql import UUID, JSONB

from app.database import Base


class DataSource(Base):
    """
    Unified registry of all external data sources (attack procedures,
    detection rules, threat intel, defensive techniques).

    Each source can be independently enabled/disabled and tracks its own
    synchronisation state.
    """
    __tablename__ = "data_sources"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = Column(String, unique=True, nullable=False)            # e.g. "atomic_red_team"
    display_name = Column(String, nullable=False)                  # e.g. "Atomic Red Team"
    type = Column(String, nullable=False)                          # attack_procedure / detection_rule / threat_intel / defensive_technique
    url = Column(String, nullable=True)                            # URL base of repo/API
    description = Column(Text, nullable=True)
    is_enabled = Column(Boolean, default=True)
    last_sync_at = Column(DateTime, nullable=True)
    last_sync_status = Column(String, nullable=True)               # success / error / in_progress
    last_sync_stats = Column(JSONB, nullable=True)                 # {"imported": X, "updated": Y, ...}
    sync_frequency = Column(String, nullable=True)                 # daily / weekly / monthly / manual
    config = Column(JSONB, nullable=True)                          # source-specific configuration
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    __table_args__ = (
        Index('ix_data_sources_type', 'type'),
        Index('ix_data_sources_is_enabled', 'is_enabled'),
    )
