"""Phase E — Send compliance-check email, with A1 ZIP-Anhang.

Original Step 6 of `_run_compliance_check`, extended with the A1
attachment: when the Tesseract pipeline captured evidence slices,
bundle them into evidence-{check_id}.zip (manifest.json +
audit_metadata.json + slice_NNN.png) and attach to the e-mail. The
attachment makes the evidence chain portable so a DSB / lawyer can
hand it to an external auditor or supervisory authority.
"""

from __future__ import annotations

import logging

from compliance.services.smtp_sender import send_email

from ._helpers import _company_name_from_url, _extract_domain, _update

logger = logging.getLogger(__name__)


def run_phase_e(state: dict) -> None:
    """Build site label, optional ZIP attachment, send mail. Mutate state."""
    check_id = state["check_id"]
    req = state["req"]
    results = state["results"]
    doc_entries = state["doc_entries"]
    full_html = state["full_html"]
    cookie_evidence_slices = state.get("cookie_evidence_slices")
    cookie_evidence_meta = state.get("cookie_evidence_meta")

    # Derive site name primarily from entered URL.
    # The extracted_profile.companyName is often noisy (e.g. picks up
    # juris.de from legal references). Domain-derived name is more
    # predictable for the GF email subject.
    doc_count = len([r for r in results if not r.error])
    url_company = _company_name_from_url(doc_entries)
    domain = _extract_domain(doc_entries)
    # Priorität: User-Input (req.company_name) > URL-Heuristik > "Unbekannt"
    req_company = (getattr(req, "company_name", None) or "").strip()
    req_domain = (getattr(req, "origin_domain", None) or "").strip()
    site_name = req_company or url_company or domain or "Unbekannt"
    if req_domain and not domain:
        # Falls keine domain aus URLs ableitbar war: User-Input verwenden
        from urllib.parse import urlparse
        try:
            domain = urlparse(req_domain).netloc.lstrip("www.") or req_domain
        except Exception:
            domain = req_domain
    _update(check_id, "E-Mail wird versendet...", 98)

    # A1: bundle cookie-evidence slices into a ZIP attachment so the
    # audit chain reaches the recipient. Each slice has its own
    # SHA-256 + capture timestamp; manifest.json + audit_metadata.json
    # make the chain verifiable for an external auditor.
    evidence_attachments: list[dict] = []
    if cookie_evidence_slices:
        try:
            from compliance.services.evidence_zip_builder import (
                build_evidence_zip,
            )
            zip_bytes = build_evidence_zip(
                slices=cookie_evidence_slices,
                meta=cookie_evidence_meta,
                check_id=check_id,
            )
            evidence_attachments.append({
                "filename": f"evidence-{check_id[:8]}.zip",
                "data": zip_bytes,
                "mime": "application/zip",
            })
        except Exception as e:
            logger.warning("A1 evidence-zip build failed: %s", e)

    # B17 audit-walk: bundle video + walk.json + README into a second
    # ZIP attachment. Reviewer hat den Beweis-Film direkt im Postfach.
    audit_walk = state.get("audit_walk")
    if audit_walk and audit_walk.get("walk_id"):
        try:
            from compliance.services.audit_walk_zip_builder import (
                build_audit_walk_zip,
            )
            walk_zip = build_audit_walk_zip(
                audit_walk,
                extra_files=_build_cookie_csv_extra(state, check_id),
            )
            if walk_zip:
                evidence_attachments.append({
                    "filename": f"audit-walk-{check_id[:8]}.zip",
                    "data": walk_zip,
                    "mime": "application/zip",
                })
        except Exception as e:
            logger.warning("audit-walk-zip build failed: %s", e)

    email_result = send_email(
        recipient=req.recipient,
        subject=f"[COMPLIANCE-CHECK] {site_name} — {doc_count} Dokumente geprueft",
        body_html=full_html,
        attachments=evidence_attachments or None,
    )

    state["email_result"] = email_result
    state["site_name"] = site_name
    state["domain"] = domain
    state["doc_count"] = doc_count


def _build_cookie_csv_extra(state: dict, check_id: str) -> dict[str, bytes]:
    """B19 Step 4: cookies-full.csv ins Walk-ZIP. Returns {filename: bytes}."""
    if not state.get("cmp_vendors"):
        return {}
    try:
        from compliance.services.cookie_csv_exporter import build_cookie_csv
        csv_bytes = build_cookie_csv(state)
        if csv_bytes:
            return {f"cookies-full-{check_id[:8]}.csv": csv_bytes}
    except Exception as e:
        logger.warning("cookie-csv build failed: %s", e)
    return {}
