"""
SQLAlchemy models for VVT — Verzeichnis von Verarbeitungstaetigkeiten (Art. 30 DSGVO).

Tables:
- compliance_vvt_organization: Organization header (DSB, version, review dates)
- compliance_vvt_activities: Individual processing activities
- compliance_vvt_audit_log: Audit trail for all VVT changes
"""

import uuid
from datetime import datetime

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

from classroom_engine.database import Base


class VVTOrganizationDB(Base):
    """VVT organization header — stores DSB contact, version and review schedule."""

    __tablename__ = 'compliance_vvt_organization'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(String(255), nullable=False, index=True)
    organization_name = Column(String(300), nullable=False)
    industry = Column(String(100))
    locations = Column(JSON, default=list)
    employee_count = Column(Integer)
    dpo_name = Column(String(200))
    dpo_contact = Column(String(200))
    vvt_version = Column(String(20), default='1.0')
    last_review_date = Column(Date)
    next_review_date = Column(Date)
    review_interval = Column(String(20), default='annual')
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    __table_args__ = (
        Index('idx_vvt_org_created', 'created_at'),
    )

    def __repr__(self):
        return f"<VVTOrganization {self.organization_name}>"


class VVTActivityDB(Base):
    """Individual processing activity per Art. 30 DSGVO."""

    __tablename__ = 'compliance_vvt_activities'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(String(255), nullable=False, index=True)
    vvt_id = Column(String(50), nullable=False)
    name = Column(String(300), nullable=False)
    description = Column(Text)
    purposes = Column(JSON, default=list)
    legal_bases = Column(JSON, default=list)
    data_subject_categories = Column(JSON, default=list)
    personal_data_categories = Column(JSON, default=list)
    recipient_categories = Column(JSON, default=list)
    third_country_transfers = Column(JSON, default=list)
    retention_period = Column(JSON, default=dict)
    tom_description = Column(Text)
    business_function = Column(String(50))
    systems = Column(JSON, default=list)
    deployment_model = Column(String(20))
    data_sources = Column(JSON, default=list)
    data_flows = Column(JSON, default=list)
    protection_level = Column(String(10), default='MEDIUM')
    dpia_required = Column(Boolean, default=False)
    structured_toms = Column(JSON, default=dict)
    status = Column(String(20), default='DRAFT')
    responsible = Column(String(200))
    owner = Column(String(200))
    last_reviewed_at = Column(DateTime(timezone=True), nullable=True)
    next_review_at = Column(DateTime(timezone=True), nullable=True)
    created_by = Column(String(200), default='system')
    dsfa_id = Column(UUID(as_uuid=True), nullable=True)

    # Library refs (Phase 1 — parallel to freetext fields)
    purpose_refs = Column(JSON, nullable=True)
    legal_basis_refs = Column(JSON, nullable=True)
    data_subject_refs = Column(JSON, nullable=True)
    data_category_refs = Column(JSON, nullable=True)
    recipient_refs = Column(JSON, nullable=True)
    retention_rule_ref = Column(String(50), nullable=True)
    transfer_mechanism_refs = Column(JSON, nullable=True)
    tom_refs = Column(JSON, nullable=True)

    # Cross-module links
    linked_loeschfristen_ids = Column(JSON, nullable=True)
    linked_tom_measure_ids = Column(JSON, nullable=True)

    # Template + risk
    source_template_id = Column(String(80), nullable=True)
    risk_score = Column(Integer, nullable=True)
    art30_completeness = Column(JSON, nullable=True)

    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    __table_args__ = (
        Index('idx_vvt_activities_status', 'status'),
        Index('idx_vvt_activities_business_function', 'business_function'),
        Index('idx_vvt_activities_tenant_status', 'tenant_id', 'status'),
    )

    def __repr__(self):
        return f"<VVTActivity {self.vvt_id}: {self.name}>"


class VVTAuditLogDB(Base):
    """Audit trail for all VVT create/update/delete/export actions."""

    __tablename__ = 'compliance_vvt_audit_log'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(String(255), nullable=False, index=True)
    action = Column(String(20), nullable=False)       # CREATE, UPDATE, DELETE, EXPORT
    entity_type = Column(String(50), nullable=False)  # activity, organization
    entity_id = Column(UUID(as_uuid=True))
    changed_by = Column(String(200))
    old_values = Column(JSON)
    new_values = Column(JSON)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)

    __table_args__ = (
        Index('idx_vvt_audit_created', 'created_at'),
        Index('idx_vvt_audit_entity', 'entity_type', 'entity_id'),
    )

    def __repr__(self):
        return f"<VVTAuditLog {self.action} {self.entity_type}>"
