import hashlib
import os
from django.db import models
from django.conf import settings
from django.utils import timezone


class AuditLog(models.Model):
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='audit_actions')
    action = models.CharField(max_length=100)
    target_type = models.CharField(max_length=100)
    target_id = models.CharField(max_length=100)
    summary = models.CharField(max_length=500)
    created_at = models.DateTimeField(default=timezone.now)
    # Phase 2: hash chain columns (nullable until backfilled)
    prev_hash = models.CharField(max_length=64, blank=True, null=True)
    row_hash = models.CharField(max_length=64, blank=True, null=True)

    class Meta:
        db_table = 'security_auditlog'
        indexes = [
            models.Index(fields=['created_at']),
        ]

    def __str__(self):
        return f"AuditLog({self.action} on {self.target_type}:{self.target_id} by {self.actor_id})"


class RateCounter(models.Model):
    """Fixed-window rate counter. key = scope:identifier."""
    key = models.CharField(max_length=255, unique=True, db_index=True)
    window_start = models.DateTimeField()
    count = models.PositiveIntegerField(default=0)

    class Meta:
        db_table = 'security_ratecounter'
        indexes = [
            models.Index(fields=['window_start']),
        ]

    def __str__(self):
        return f"RateCounter({self.key}, count={self.count})"


class Setting(models.Model):
    """Runtime-configurable settings (e.g. rate limit thresholds)."""
    key = models.CharField(max_length=100, unique=True)
    value = models.TextField()
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, blank=True, related_name='setting_changes'
    )

    class Meta:
        db_table = 'security_setting'

    def __str__(self):
        return f"Setting({self.key}={self.value})"


class SecurityEvent(models.Model):
    """Immutable security event log. Never stores raw IP or message bodies."""
    event_type = models.CharField(max_length=100, db_index=True)
    ip_hash = models.CharField(max_length=64, blank=True, null=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, blank=True, related_name='security_events'
    )
    path = models.CharField(max_length=255, blank=True, default='')
    meta = models.TextField(max_length=1000, blank=True, default='')
    created_at = models.DateTimeField(default=timezone.now, db_index=True)

    class Meta:
        db_table = 'security_securityevent'
        indexes = [
            models.Index(fields=['event_type', 'created_at']),
            models.Index(fields=['ip_hash', 'created_at']),
        ]

    def __str__(self):
        return f"SecurityEvent({self.event_type} at {self.created_at})"


class DailySalt(models.Model):
    """Daily salt for IP hashing. Rotated by cron at 00:05 each day."""
    day = models.DateField(unique=True, db_index=True)
    salt = models.CharField(max_length=64)  # 32 bytes hex

    class Meta:
        db_table = 'security_dailysalt'

    def __str__(self):
        return f"DailySalt({self.day})"


class LegalDocument(models.Model):
    DOC_TYPES = [('privacy', 'Privacy Policy'), ('terms', 'Terms & Conditions')]
    STATUS_CHOICES = [('draft', 'Draft'), ('published', 'Published')]

    doc_type = models.CharField(max_length=20, choices=DOC_TYPES)
    version = models.CharField(max_length=20)
    title = models.CharField(max_length=80)
    effective_date = models.DateField(null=True, blank=True)
    intro = models.TextField(max_length=400, blank=True, default='')
    # JSON: list of {"key": str, "title": str, "body": str}
    sections = models.JSONField(default=list)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
    change_note = models.CharField(max_length=240, blank=True, default='')
    published_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, blank=True, related_name='legal_documents'
    )
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'core_legaldocument'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['doc_type', 'status']),
        ]

    def __str__(self):
        return f"LegalDocument({self.doc_type} v{self.version} [{self.status}])"
