import hashlib
import json
import secrets
from datetime import timedelta
from urllib.request import Request, urlopen

from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.mail import EmailMessage
from django.utils import timezone

from apps.document_engine.models import (
    DocumentDeliveryChannel,
    DocumentDeliveryLog,
    DocumentDeliveryRule,
    DocumentShareLink,
    DocumentVersion,
)
from apps.document_engine.services.archive_service import decrypt_secret, encrypt_secret, read_encrypted_blob


def _append_timeline(log: DocumentDeliveryLog, status: str, note: str = "") -> None:
    tl = list(log.timeline or [])
    tl.append({"status": status, "timestamp": timezone.now().isoformat(), "note": note})
    log.timeline = tl
    log.status = status


def create_share_link(*, company, document_version: DocumentVersion, user, hours_valid: int = 72, max_downloads: int = 10, recipient_hint: str = "") -> tuple[DocumentShareLink, str]:
    raw_token = secrets.token_urlsafe(32)
    token_hash = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
    link = DocumentShareLink.objects.create(
        company=company,
        document_version=document_version,
        token_hash=token_hash,
        recipient_hint=recipient_hint,
        expires_at=timezone.now() + timedelta(hours=max(1, min(720, hours_valid))),
        max_downloads=max(1, max_downloads),
        created_by=user,
    )
    return link, raw_token


def dispatch_delivery(
    *,
    company,
    document_version: DocumentVersion,
    channel_type: str,
    recipient: str,
    user,
    subject: str = "",
    message_body: str = "",
    channel_id=None,
    ip_address: str | None = None,
) -> DocumentDeliveryLog:
    """Deliver a frozen DocumentVersion via Email, WhatsApp, Portal Share Link, or Print Queue."""
    from apps.document_engine.services.pdf_service import log_document_audit

    if document_version.company_id != company.id:
        raise ValidationError("Cross-company document delivery blocked.")

    channel = (
        DocumentDeliveryChannel.objects.filter(company=company, id=channel_id, is_enabled=True).first()
        if channel_id
        else DocumentDeliveryChannel.objects.filter(company=company, channel_type=channel_type, is_enabled=True).first()
    )

    rec = document_version.document_record
    subj = subject or f"{rec.document_type.name} {rec.document_number or ''} — {company.name}"
    body = message_body or f"Please find attached {rec.document_type.name} ({rec.document_number or ''})."

    log = DocumentDeliveryLog.objects.create(
        company=company,
        document_version=document_version,
        channel=channel,
        channel_type=channel_type,
        recipient=recipient,
        subject=subj,
        status=DocumentDeliveryLog.Status.QUEUED,
        timeline=[
            {"status": DocumentDeliveryLog.Status.GENERATED, "timestamp": timezone.now().isoformat(), "note": f"Version v{document_version.version_number}"},
            {"status": DocumentDeliveryLog.Status.QUEUED, "timestamp": timezone.now().isoformat(), "note": f"Channel {channel_type}"},
        ],
        dispatched_by=user,
    )

    try:
        file_bytes = read_encrypted_blob(storage_key=document_version.storage_key)

        if channel_type == DocumentDeliveryChannel.ChannelType.EMAIL:
            if not recipient or "@" not in recipient:
                raise ValidationError("Valid recipient email address is required.")
            from_email = (
                channel.sender_identity
                if channel and channel.sender_identity
                else getattr(settings, "DEFAULT_FROM_EMAIL", "noreply@mayaos.local")
            )
            email = EmailMessage(subject=subj, body=body, from_email=from_email, to=[recipient])
            email.attach(document_version.file_name, file_bytes, document_version.mime_type)
            email.send(fail_silently=False)
            _append_timeline(log, DocumentDeliveryLog.Status.SENT, f"Email dispatched to {recipient}")

        elif channel_type == DocumentDeliveryChannel.ChannelType.WHATSAPP:
            clean_phone = "".join(ch for ch in recipient if ch.isdigit() or ch == "+")
            if len(clean_phone) < 8:
                raise ValidationError("Valid WhatsApp recipient phone number is required.")
            _, raw_tok = create_share_link(company=company, document_version=document_version, user=user, recipient_hint=clean_phone)
            if channel and channel.endpoint_or_host.startswith("http"):
                token = decrypt_secret(channel.encrypted_credentials) if channel.encrypted_credentials else ""
                req = Request(
                    channel.endpoint_or_host,
                    data=json.dumps(
                        {
                            "to": clean_phone,
                            "message": f"{body} Portal token: {raw_tok}",
                            "document": document_version.file_name,
                        }
                    ).encode("utf-8"),
                    headers={
                        "Content-Type": "application/json",
                        **({"Authorization": f"Bearer {token}"} if token else {}),
                    },
                    method="POST",
                )
                with urlopen(req, timeout=10) as resp:  # noqa: S310
                    log.provider_message_id = str(resp.status)
            else:
                log.provider_message_id = f"wa-sim-{secrets.token_hex(6)}"
            _append_timeline(log, DocumentDeliveryLog.Status.SENT, f"WhatsApp message queued for {clean_phone}")

        elif channel_type == DocumentDeliveryChannel.ChannelType.PORTAL:
            link, raw_tok = create_share_link(company=company, document_version=document_version, user=user, recipient_hint=recipient)
            log.provider_message_id = raw_tok
            _append_timeline(log, DocumentDeliveryLog.Status.DELIVERED, f"Expiring portal link issued (expires {link.expires_at.date().isoformat()})")

        else:
            _append_timeline(log, DocumentDeliveryLog.Status.SENT, f"Processed via {channel_type}")

        log.save()
        log_document_audit(
            company=company,
            actor=user,
            action="DELIVERED" if channel_type == "PORTAL" else "SENT",
            doc_type_code=rec.document_type.code,
            source_id=rec.source_id,
            document_number=rec.document_number or "",
            output_format=document_version.output_format,
            details={"channel": channel_type, "recipient": recipient, "delivery_log_id": str(log.id)},
            ip_address=ip_address,
        )
    except Exception as exc:
        log.failure_reason = str(exc)
        _append_timeline(log, DocumentDeliveryLog.Status.FAILED, str(exc))
        log.save()
        log_document_audit(
            company=company,
            actor=user,
            action="DELIVERY_FAILED",
            doc_type_code=rec.document_type.code,
            source_id=rec.source_id,
            document_number=rec.document_number or "",
            output_format=document_version.output_format,
            details={"channel": channel_type, "recipient": recipient, "error": str(exc)},
            ip_address=ip_address,
        )
    return log


def trigger_event_delivery_rules(*, company, event_trigger: str, source_id: str, recipient: str, user) -> list[DocumentDeliveryLog]:
    """Execute configured automated document generation & distribution rules cleanly."""
    from apps.document_engine.services.pdf_service import generate_pdf_document

    rules = DocumentDeliveryRule.objects.select_related("document_type", "channel").filter(
        company=company, event_trigger=event_trigger, is_active=True
    )
    logs = []
    for rule in rules:
        if not rule.auto_generate_pdf:
            continue
        _, version_obj, _ = generate_pdf_document(
            company=company,
            doc_type_code=rule.document_type.code,
            source_id=source_id,
            user=user,
            action_label="AUTO_GENERATED",
        )
        if rule.auto_send and version_obj and recipient:
            logs.append(
                dispatch_delivery(
                    company=company,
                    document_version=version_obj,
                    channel_type=rule.channel.channel_type,
                    recipient=recipient,
                    user=user,
                    channel_id=rule.channel_id,
                )
            )
    return logs


def save_channel_credentials(channel: DocumentDeliveryChannel, secret_value: str) -> None:
    if secret_value:
        channel.encrypted_credentials = encrypt_secret(secret_value)
        channel.save(update_fields=["encrypted_credentials", "updated_at"])
