"""
security/services.py - Phase 2 security services.
Raw IP addresses never leave this module. Only salted SHA-256 hashes are stored.
"""
import hashlib
import json
import logging
import os
import csv
import io
from datetime import timedelta

from django.conf import settings
from django.utils import timezone
from django.core.cache import cache

logger = logging.getLogger(__name__)


class RetryAfter(Exception):
    def __init__(self, retry_after_seconds):
        self.retry_after = retry_after_seconds
        super().__init__(f"Rate limit exceeded. Retry after {retry_after_seconds}s.")


class CaptchaUnavailable(Exception):
    pass


# ---------------------------------------------------------------------------
# Audit log (hash-chained, append-only)
# ---------------------------------------------------------------------------

def _compute_row_hash(prev_hash, actor_id, action, target_type, target_id, summary, created_at):
    data = f"{prev_hash or ''}|{actor_id or ''}|{action}|{target_type}|{target_id}|{summary}|{created_at.isoformat()}"
    return hashlib.sha256(data.encode('utf-8')).hexdigest()


def log_audit(actor, action, target_type, target_id, summary=None, details=None):
    """Append-only audit log writer with hash chain. No IP address is logged."""
    from core.models import AuditLog
    if summary is None and details is not None:
        summary = json.dumps(details) if isinstance(details, (dict, list)) else str(details)
    summary = str(summary)[:500] if summary else ""
    prev_hash = None
    try:
        last = AuditLog.objects.order_by('-id').first()
        if last:
            prev_hash = last.row_hash
    except Exception:
        pass

    created_at = timezone.now()
    row_hash = None
    try:
        actor_id = actor.id if actor else None
        row_hash = _compute_row_hash(
            prev_hash, actor_id, action, target_type, str(target_id), summary, created_at
        )
    except Exception:
        pass

    return AuditLog.objects.create(
        actor=actor,
        action=action,
        target_type=target_type,
        target_id=str(target_id),
        summary=summary,
        created_at=created_at,
        prev_hash=prev_hash,
        row_hash=row_hash,
    )


def verify_chain():
    """Return first broken AuditLog row ID, or None if intact."""
    from core.models import AuditLog
    rows = AuditLog.objects.order_by('id').values(
        'id', 'actor_id', 'action', 'target_type', 'target_id',
        'summary', 'created_at', 'prev_hash', 'row_hash'
    )
    expected_prev = None
    for row in rows:
        if row['row_hash'] is None:
            expected_prev = None
            continue
        if row['prev_hash'] != expected_prev:
            return row['id']
        computed = _compute_row_hash(
            row['prev_hash'], row['actor_id'], row['action'],
            row['target_type'], row['target_id'], row['summary'],
            row['created_at']
        )
        if computed != row['row_hash']:
            return row['id']
        expected_prev = row['row_hash']
    return None


def backfill_audit_chain():
    """One-time migration: compute hashes for all AuditLog rows without hash."""
    from core.models import AuditLog
    rows = AuditLog.objects.order_by('id')
    prev_hash = None
    for row in rows:
        if row.row_hash:
            prev_hash = row.row_hash
            continue
        row_hash = _compute_row_hash(
            prev_hash, row.actor_id, row.action, row.target_type,
            row.target_id, row.summary, row.created_at
        )
        row.prev_hash = prev_hash
        row.row_hash = row_hash
        row.save(update_fields=['prev_hash', 'row_hash'])
        prev_hash = row_hash
    return True


def export_audit_csv(from_date, to_date, actor):
    from core.models import AuditLog
    qs = AuditLog.objects.order_by('id')
    if from_date:
        qs = qs.filter(created_at__gte=from_date)
    if to_date:
        qs = qs.filter(created_at__lte=to_date)
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(['id', 'actor', 'action', 'target_type', 'target_id', 'summary', 'created_at', 'prev_hash', 'row_hash'])
    for row in qs.values('id', 'actor__username', 'action', 'target_type', 'target_id', 'summary', 'created_at', 'prev_hash', 'row_hash'):
        writer.writerow([
            row['id'], row['actor__username'] or '', row['action'],
            row['target_type'], row['target_id'], row['summary'],
            row['created_at'].isoformat() if row['created_at'] else '',
            row['prev_hash'] or '', row['row_hash'] or ''
        ])
    csv_text = output.getvalue()
    log_audit(actor, 'export_audit_csv', 'AuditLog', 'export',
              f"Exported audit log from {from_date} to {to_date}")
    return csv_text


def export_security_csv(from_date, to_date, actor):
    from core.models import SecurityEvent
    qs = SecurityEvent.objects.order_by('id')
    if from_date:
        qs = qs.filter(created_at__gte=from_date)
    if to_date:
        qs = qs.filter(created_at__lte=to_date)
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(['id', 'event_type', 'ip_hash', 'user', 'path', 'meta', 'created_at'])
    for row in qs.values('id', 'event_type', 'ip_hash', 'user__username', 'path', 'meta', 'created_at'):
        writer.writerow([
            row['id'], row['event_type'], row['ip_hash'] or '',
            row['user__username'] or '', row['path'], row['meta'],
            row['created_at'].isoformat() if row['created_at'] else ''
        ])
    return output.getvalue()


# ---------------------------------------------------------------------------
# Daily salt + IP hashing
# ---------------------------------------------------------------------------

def _get_or_create_daily_salt():
    from core.models import DailySalt
    today = timezone.now().date()
    salt_obj, _ = DailySalt.objects.get_or_create(
        day=today,
        defaults={'salt': os.urandom(32).hex()}
    )
    return salt_obj.salt


def ip_hash(request):
    """Return SHA-256(daily_salt + client_ip). Raw IP never stored."""
    salt = _get_or_create_daily_salt()
    xff = request.META.get('HTTP_X_FORWARDED_FOR', '')
    if xff:
        client_ip = xff.split(',')[0].strip()
    else:
        client_ip = request.META.get('REMOTE_ADDR', '')
    return hashlib.sha256(f"{salt}{client_ip}".encode('utf-8')).hexdigest()


# ---------------------------------------------------------------------------
# Settings (runtime-configurable, cached 60s)
# ---------------------------------------------------------------------------

_SETTING_DEFAULTS = {
    'rate_limit.login': '10',
    'rate_limit.registration': '5',
    'rate_limit.anon_submission_ip': '5',
    'rate_limit.anon_submission_inbox': '20',
    'rate_limit.password_reset': '3',
    'rate_limit.resend_verification': '1',
    'rate_limit.direct_message': '30',
    'rate_limit.username_check': '30',
    'adaptive_threshold': '1000',
    'captcha_enabled': 'true',
}

_SETTING_CACHE_KEY = 'security_settings'
_SETTING_CACHE_TTL = 60


def _load_settings_from_db():
    from core.models import Setting
    result = dict(_SETTING_DEFAULTS)
    for s in Setting.objects.all():
        result[s.key] = s.value
    return result


def _get_all_settings():
    cached = cache.get(_SETTING_CACHE_KEY)
    if cached is None:
        cached = _load_settings_from_db()
        cache.set(_SETTING_CACHE_KEY, cached, _SETTING_CACHE_TTL)
    return cached


def get_setting(key):
    return _get_all_settings().get(key, _SETTING_DEFAULTS.get(key, ''))


def set_setting(actor, key, value):
    from core.models import Setting
    old_value = get_setting(key)
    Setting.objects.update_or_create(
        key=key,
        defaults={'value': str(value), 'updated_by': actor}
    )
    cache.delete(_SETTING_CACHE_KEY)
    log_audit(actor, 'settings.update', key, 'setting',
              f"Changed from {old_value} to {value}")


# ---------------------------------------------------------------------------
# Rate limiting
# ---------------------------------------------------------------------------

def _is_adaptive_active():
    try:
        threshold = int(get_setting('adaptive_threshold') or 1000)
        five_min_ago = timezone.now() - timedelta(minutes=5)
        from core.models import SecurityEvent
        count = SecurityEvent.objects.filter(created_at__gte=five_min_ago).count()
        return count > threshold
    except Exception:
        return False


def rate_limit(key, limit, window_seconds):
    """
    Fixed-window rate limiter. Raises RetryAfter if limit exceeded.
    key: unique string e.g. 'login:ip_hash_xyz'
    """
    from core.models import RateCounter
    now = timezone.now()
    window_start_threshold = now - timedelta(seconds=window_seconds)

    if _is_adaptive_active():
        limit = max(1, limit // 2)

    counter, created = RateCounter.objects.get_or_create(
        key=key,
        defaults={'window_start': now, 'count': 0}
    )

    if counter.window_start < window_start_threshold:
        counter.window_start = now
        counter.count = 0

    counter.count += 1
    counter.save(update_fields=['window_start', 'count'])

    if counter.count > limit:
        seconds_remaining = int(
            (counter.window_start + timedelta(seconds=window_seconds) - now).total_seconds()
        )
        seconds_remaining = max(1, seconds_remaining)
        raise RetryAfter(seconds_remaining)


# ---------------------------------------------------------------------------
# CAPTCHA
# ---------------------------------------------------------------------------

def verify_captcha(token, remote_hash=None):
    """
    Verify CAPTCHA token with provider. Returns True if valid.
    Raises CaptchaUnavailable on timeout. Single-use enforced via cache.
    If settings.CAPTCHA_ENABLED=False, always returns True.
    """
    captcha_enabled = getattr(settings, 'CAPTCHA_ENABLED', True)
    if not captcha_enabled:
        return True

    if not token:
        return False

    used_key = f"captcha_used:{token}"
    if cache.get(used_key):
        return False

    provider_url = getattr(settings, 'CAPTCHA_VERIFY_URL', 'https://hcaptcha.com/siteverify')
    secret = getattr(settings, 'CAPTCHA_SECRET_KEY', '')

    try:
        import requests as _requests
        resp = _requests.post(
            provider_url,
            data={'secret': secret, 'response': token},
            timeout=5
        )
        data = resp.json()
        success = bool(data.get('success', False))
    except Exception as exc:
        logger.warning(f"CAPTCHA provider error: {exc}")
        raise CaptchaUnavailable(str(exc))

    if success:
        cache.set(used_key, True, 600)

    return success


# ---------------------------------------------------------------------------
# Security events
# ---------------------------------------------------------------------------

def log_security_event(event_type, request=None, user=None, meta=None):
    """Write a SecurityEvent. Never raises - failures go to application log."""
    try:
        from core.models import SecurityEvent
        ip_hash_val = None
        path = ''
        if request is not None:
            try:
                ip_hash_val = ip_hash(request)
                path = str(request.path)[:255]
            except Exception:
                pass
        meta_str = ''
        if meta is not None:
            try:
                meta_str = json.dumps(meta)[:1000]
            except Exception:
                meta_str = str(meta)[:1000]
        SecurityEvent.objects.create(
            event_type=event_type,
            ip_hash=ip_hash_val,
            user=user,
            path=path,
            meta=meta_str,
        )
    except Exception as exc:
        logger.error(f"log_security_event failed: {exc}")


def count_events(since):
    from core.models import SecurityEvent
    return SecurityEvent.objects.filter(created_at__gte=since).count()


def count_suspicious():
    from core.models import SecurityEvent
    from django.db.models import Count
    ten_min_ago = timezone.now() - timedelta(minutes=10)
    return (
        SecurityEvent.objects
        .filter(created_at__gte=ten_min_ago, ip_hash__isnull=False)
        .values('ip_hash')
        .annotate(cnt=Count('id'))
        .filter(cnt__gte=20)
        .count()
    )
