"""Phase D-3-Mid — Mid HTML blocks (P62/P103/P104/P105/audit/mismatch/signals).

Covers (in the original Step 5):
  - P62 Scope-Disclaimer
  - P103 Cookie-Value-Entropy + P104 Network-Tracing
  - P105 IAB TCF Authority cross-reference
  - Cookie-Compliance-Audit (3-Quellen-Vergleich, central USP)
  - P102 Cookie-Klassifikations-Pruefung (library mismatch)
  - P35/P77/P78 Doc-Text signals
  - P92/P94 Banner-Konsistenz
  - P73 MC-Solution-Generator (LLM suggestions per HIGH-Fail)
"""

from __future__ import annotations

import logging

logger = logging.getLogger(__name__)


async def run_phase_d3_mid(state: dict) -> None:
    """Mid HTML blocks. Mutates state in place."""
    doc_entries = state["doc_entries"]
    doc_texts = state["doc_texts"]
    banner_result = state["banner_result"]
    cmp_vendors = state["cmp_vendors"]
    fails_by_doc = state["fails_by_doc"]
    html_blocks = state["html_blocks"]

    # P62: Marketing-Manager-Disclaimer
    scope_disclaimer_html = ""
    try:
        from ..scope_disclaimer import build_scope_disclaimer_html
        scope_disclaimer_html = build_scope_disclaimer_html()
    except Exception as e:
        logger.warning("Scope-disclaimer block skipped: %s", e)

    # P103 + P104 — Cookie-Value-Entropy + Network-Tracing
    entropy_html = ""
    network_trace_html = ""
    try:
        from compliance.services.cookie_network_tracer import (
            build_network_trace_block_html,
            trace_cookie_network,
        )
        from compliance.services.cookie_value_entropy import (
            build_entropy_block_html,
            check_cookies_for_entropy_mismatch,
        )
        cookies_detailed = (banner_result or {}).get("cookies_detailed") or []
        entropy_findings = check_cookies_for_entropy_mismatch(cookies_detailed)
        if entropy_findings:
            entropy_html = build_entropy_block_html(entropy_findings)
            logger.info("P103 Entropy: %d Findings", len(entropy_findings))
        primary_url = ""
        for e_ in doc_entries:
            if e_.get("url"):
                primary_url = e_["url"]; break
        net_findings = trace_cookie_network(cookies_detailed, primary_url)
        if net_findings:
            network_trace_html = build_network_trace_block_html(net_findings)
            logger.info("P104 Network-Trace: %d Findings", len(net_findings))
    except Exception as e:
        logger.warning("P103/P104 entropy/network-trace skipped: %s", e)

    # P105 — IAB TCF Authority-Cross-Reference
    tcf_authority_html = ""
    try:
        from compliance.services.tcf_vendor_authority import (
            build_tcf_authority_block_html, cross_reference_with_tcf,
        )
        from database import SessionLocal as _SLtcf
        _tcf_db = _SLtcf()
        try:
            tcf_findings = cross_reference_with_tcf(_tcf_db, cmp_vendors)
            if tcf_findings:
                tcf_authority_html = build_tcf_authority_block_html(tcf_findings)
                logger.info(
                    "TCF-Authority: %d Vendor-Discrepancies gefunden",
                    len(tcf_findings),
                )
        finally:
            _tcf_db.close()
    except Exception as e:
        logger.warning("TCF-Authority-Check skipped: %s", e)

    # COOKIE-COMPLIANCE-AUDIT (3-Quellen-Vergleich — central USP)
    cookie_audit: dict = {}
    cookie_audit_html = ""
    try:
        from compliance.services.cookie_compliance_audit import (
            audit_cookie_compliance, build_cookie_audit_block_html,
        )
        from database import SessionLocal as _SLca
        _ca_db = _SLca()
        try:
            cookie_audit = audit_cookie_compliance(
                _ca_db, doc_texts.get("cookie") or doc_texts.get("dse"),
                banner_result,
            )
            if cookie_audit and (cookie_audit.get("declared_count") or
                                  cookie_audit.get("browser_count")):
                cookie_audit_html = build_cookie_audit_block_html(cookie_audit)
                logger.info(
                    "Cookie-Audit: %d deklariert, %d im Browser, "
                    "%d undokumentiert, %d compliant",
                    cookie_audit.get("declared_count"),
                    cookie_audit.get("browser_count"),
                    len(cookie_audit.get("undeclared_in_browser") or []),
                    len(cookie_audit.get("compliant") or []),
                )
        finally:
            _ca_db.close()
    except Exception as e:
        logger.warning("cookie-compliance-audit skipped: %s", e)

    # P102: Cookie-Klassifikations-Pruefung
    library_mismatch_html = ""
    mismatches: list[dict] = []
    try:
        from compliance.services.cookie_library_mismatch import (
            build_mismatch_block_html, detect_mismatches,
        )
        from database import SessionLocal
        cookie_doc_for_check = doc_texts.get("cookie") or doc_texts.get("dse") or ""
        all_cookies_seen: list[str] = []
        if banner_result:
            for ph in (banner_result.get("phases") or {}).values():
                if isinstance(ph, dict):
                    for ck in (ph.get("cookies") or []):
                        if isinstance(ck, str):
                            all_cookies_seen.append(ck)
                        elif isinstance(ck, dict) and ck.get("name"):
                            all_cookies_seen.append(ck["name"])
        if all_cookies_seen and cookie_doc_for_check:
            _mm_db = SessionLocal()
            try:
                mismatches = detect_mismatches(
                    _mm_db, all_cookies_seen, cookie_doc_for_check,
                )
                if mismatches:
                    library_mismatch_html = build_mismatch_block_html(mismatches)
                    logger.info(
                        "P102: %d Cookie-Mismatches gefunden", len(mismatches),
                    )
            finally:
                _mm_db.close()
    except Exception as e:
        logger.warning("P102 mismatch detection failed: %s", e)

    # P35 + P77 + P78: Textsignal-Checks
    signals_html = ""
    try:
        from compliance.services.doc_text_signals import (
            build_signals_block_html, run_all as run_signal_checks,
        )
        cookie_doc_missing = not bool(doc_texts.get("cookie"))
        sig_findings = run_signal_checks(
            banner_result, doc_texts, cookie_doc_missing,
        )
        if sig_findings:
            signals_html = build_signals_block_html(sig_findings)
    except Exception as e:
        logger.warning("P35/P77/P78 signals-check failed: %s", e)

    # P92 + P94: Banner-Konsistenz
    consistency_html = ""
    try:
        from compliance.services.banner_consistency_checks import (
            build_consistency_block_html, run_all as run_consistency_checks,
        )
        cookie_doc_for_check = (doc_texts.get("cookie")
                                or doc_texts.get("dse") or "")
        cons_findings = run_consistency_checks(
            banner_result or {}, cookie_doc_for_check, cmp_vendors,
            doc_texts=doc_texts,
        )
        if cons_findings:
            consistency_html = build_consistency_block_html(cons_findings)
            logger.info("P92/P94: %d Konsistenz-Findings", len(cons_findings))
    except Exception as e:
        logger.warning("P92/P94 consistency-check failed: %s", e)

    # P73: MC-Solution-Generator — LLM-Vorschlaege pro HIGH-Fail
    solutions_html = ""
    try:
        from compliance.services.mc_solution_generator import (
            build_solutions_block_html, generate_solutions_for_fails,
        )
        all_solutions: list[dict] = []
        for dt, fails in fails_by_doc.items():
            if not fails:
                continue
            doc_txt = doc_texts.get(dt) or doc_texts.get("dse") or ""
            if not doc_txt or len(doc_txt) < 500:
                continue
            sols = await generate_solutions_for_fails(
                fails, doc_txt, dt, limit=3,
            )
            all_solutions.extend(sols)
            if len(all_solutions) >= 8:
                break
        if all_solutions:
            solutions_html = build_solutions_block_html(all_solutions[:8])
            logger.info("P73: %d MC-Solutions generiert", len(all_solutions))
    except Exception as e:
        logger.warning("P73 MC-Solution-Generator skipped: %s", e)

    html_blocks.update({
        "scope_disclaimer_html": scope_disclaimer_html,
        "entropy_html": entropy_html,
        "network_trace_html": network_trace_html,
        "tcf_authority_html": tcf_authority_html,
        "cookie_audit_html": cookie_audit_html,
        "library_mismatch_html": library_mismatch_html,
        "signals_html": signals_html,
        "consistency_html": consistency_html,
        "solutions_html": solutions_html,
    })
    state["cookie_audit"] = cookie_audit
    state["mismatches"] = mismatches
