"""
SQLAlchemy models for Banner Consent — Device-basierte Cookie-Consents.

Tables:
- compliance_banner_consents: Anonyme Geraete-Consents
- compliance_banner_consent_audit_log: Immutable Audit
- compliance_banner_site_configs: Site-Konfiguration
- compliance_banner_category_configs: Consent-Kategorien pro Site
- compliance_banner_vendor_configs: Third-Party-Vendor-Tracking
"""

import uuid
from datetime import datetime

from sqlalchemy import (
    Column, Text, Boolean, Integer, DateTime, Index, JSON
)
from sqlalchemy.dialects.postgresql import UUID

from classroom_engine.database import Base


class BannerConsentDB(Base):
    """Anonymer Device-basierter Cookie-Consent."""

    __tablename__ = 'compliance_banner_consents'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(UUID(as_uuid=True), nullable=False)
    site_id = Column(Text, nullable=False)
    device_fingerprint = Column(Text, nullable=False)
    categories = Column(JSON, default=list)
    vendors = Column(JSON, default=list)
    vendor_consents = Column(JSON, default=dict)  # {"vendor_id": true/false}
    ip_hash = Column(Text)
    user_agent = Column(Text)
    consent_string = Column(Text)
    linked_email = Column(Text)
    # Vendor-agnostische Felder (Migration 107)
    consent_method = Column(Text)          # accept_all / reject_all / custom_selection
    banner_version = Column(Integer)
    banner_config_hash = Column(Text)
    geo_country = Column(Text)
    geo_region = Column(Text)
    consent_scope = Column(Text, default='domain')
    page_url = Column(Text)
    referrer = Column(Text)
    device_type = Column(Text)             # mobile / desktop / tablet
    browser = Column(Text)
    os = Column(Text)
    screen_resolution = Column(Text)
    session_id = Column(Text)
    # Script/Cookie-Tracking (Migration 108)
    scripts_blocked = Column(JSON, default=list)
    scripts_released = Column(JSON, default=list)
    cookies_set = Column(JSON, default=list)
    expires_at = Column(DateTime)
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    __table_args__ = (
        Index('idx_banner_consent_tenant', 'tenant_id'),
        Index('idx_banner_consent_site', 'site_id'),
        Index('idx_banner_consent_device', 'device_fingerprint'),
        Index('idx_banner_consent_email', 'linked_email',
              postgresql_where='linked_email IS NOT NULL'),
    )


class BannerConsentAuditLogDB(Base):
    """Immutable Audit-Trail fuer Banner-Consents."""

    __tablename__ = 'compliance_banner_consent_audit_log'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(UUID(as_uuid=True), nullable=False)
    consent_id = Column(UUID(as_uuid=True))
    action = Column(Text, nullable=False)
    site_id = Column(Text, nullable=False)
    device_fingerprint = Column(Text)
    categories = Column(JSON, default=list)
    vendor_consents = Column(JSON, default=dict)
    ip_hash = Column(Text)
    user_agent = Column(Text)
    banner_config_hash = Column(Text)
    consent_version = Column(Integer)
    consent_method = Column(Text)
    page_url = Column(Text)
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)

    __table_args__ = (
        Index('idx_banner_audit_tenant', 'tenant_id'),
        Index('idx_banner_audit_site', 'site_id'),
        Index('idx_banner_audit_created', 'created_at'),
    )


class BannerSiteConfigDB(Base):
    """Site-Konfiguration fuer Consent-Banner."""

    __tablename__ = 'compliance_banner_site_configs'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(UUID(as_uuid=True), nullable=False)
    site_id = Column(Text, nullable=False)
    site_name = Column(Text)
    site_url = Column(Text)
    banner_title = Column(Text, default='Cookie-Einstellungen')
    banner_description = Column(Text, default='Wir verwenden Cookies, um Ihnen die bestmoegliche Erfahrung zu bieten.')
    privacy_url = Column(Text)
    imprint_url = Column(Text)
    dsb_name = Column(Text)
    dsb_email = Column(Text)
    theme = Column(JSON, default=dict)
    tcf_enabled = Column(Boolean, default=False)
    config_version = Column(Integer, nullable=False, default=1)
    is_active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    __table_args__ = (
        Index('idx_banner_site_config', 'tenant_id', 'site_id', unique=True),
    )


class BannerCategoryConfigDB(Base):
    """Consent-Kategorien pro Site."""

    __tablename__ = 'compliance_banner_category_configs'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    site_config_id = Column(UUID(as_uuid=True), nullable=False)
    category_key = Column(Text, nullable=False)
    name_de = Column(Text, nullable=False)
    name_en = Column(Text)
    description_de = Column(Text)
    description_en = Column(Text)
    is_required = Column(Boolean, nullable=False, default=False)
    sort_order = Column(Integer, nullable=False, default=0)
    is_active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)

    __table_args__ = (
        Index('idx_banner_cat_config', 'site_config_id'),
    )


class BannerVendorConfigDB(Base):
    """Third-Party-Vendor-Tracking pro Site."""

    __tablename__ = 'compliance_banner_vendor_configs'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    site_config_id = Column(UUID(as_uuid=True), nullable=False)
    vendor_name = Column(Text, nullable=False)
    vendor_url = Column(Text)
    category_key = Column(Text, nullable=False)
    description_de = Column(Text)
    description_en = Column(Text)
    cookie_names = Column(JSON, default=list)
    retention_days = Column(Integer, default=365)
    is_active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)

    __table_args__ = (
        Index('idx_banner_vendor_config', 'site_config_id'),
    )
