"""Bridge gate between source governance and fetch target review.

This module only cross-checks two operator supplied review summaries:
professional source governance and MCP fetch target review. It does not
fetch external pages, read robots/sitemap, open DB connections, persist
payloads, execute CLI commands, or attach schedulers.
"""

from services.market_intel.mcp_fetch_target_review import (
    build_mcp_fetch_target_review_preview,
)
from services.market_intel.mcp_professional_source_governance import (
    build_mcp_professional_source_governance_preview,
)


def _as_dict(value):
    return value if isinstance(value, dict) else {}


def _as_list(value):
    return value if isinstance(value, list) else []


def _unwrap_source_governance_package(package):
    package = _as_dict(package)
    return (
        package.get("operator_source_governance")
        or package.get("source_governance")
        or package.get("market_source_governance")
        or package
    )


def _target_package_from_input(package):
    package = _as_dict(package)
    return {
        "handoff_package": package.get("handoff_package", {}),
        "handoff_review": package.get("handoff_review"),
        "target_review": (
            package
            if "platform_targets" in package
            else package.get("target_review", {})
        ),
    }


def _target_sources(target_review):
    target_review = _as_dict(target_review)
    sources = []
    for target in _as_list(target_review.get("platform_targets")):
        if not isinstance(target, dict):
            continue
        platform_code = str(target.get("platform_code") or "").lower()
        source_keys = target.get("source_keys") or []
        if isinstance(source_keys, str):
            source_keys = [source_keys]
        for source_key in source_keys:
            if platform_code and source_key:
                sources.append(
                    {
                        "platform_code": platform_code,
                        "source_key": str(source_key),
                    }
                )
    return sources


def _governed_source_index(source_governance):
    return {
        (
            source.get("platform_code"),
            source.get("source_key"),
        )
        for source in _as_list(source_governance.get("sources"))
        if source.get("platform_code") and source.get("source_key")
    }


def _source_alignment(target_sources, source_governance):
    governed = _governed_source_index(source_governance)
    missing = [
        source
        for source in target_sources
        if (source["platform_code"], source["source_key"]) not in governed
    ]
    return {
        "target_sources": target_sources,
        "governed_source_count": len(governed),
        "target_source_count": len(target_sources),
        "missing_governed_sources": missing,
        "all_target_sources_governed": bool(target_sources and not missing),
    }


def _sample_package():
    source_governance = build_mcp_professional_source_governance_preview()
    target_review = build_mcp_fetch_target_review_preview()
    return {
        "professional_source_governance_package": source_governance[
            "sample_professional_source_governance_package"
        ],
        "target_review_package": target_review["sample_target_review_package"],
        "operator_confirmations": {
            "source_governance_reviewed": True,
            "target_review_reviewed": True,
            "all_target_sources_reference_governed_sources": True,
            "no_api_external_fetch": True,
            "no_database_write": True,
            "no_scheduler_attach": True,
        },
    }


def build_mcp_fetch_target_source_governance_review_preview(
    *,
    professional_source_governance_package=None,
    target_review_package=None,
    operator_confirmations=None,
    phase=None,
):
    """Review target/source governance alignment without side effects."""
    source_package_received = professional_source_governance_package is not None
    target_package_received = target_review_package is not None
    confirmations = _as_dict(operator_confirmations)
    source_governance = build_mcp_professional_source_governance_preview(
        operator_source_governance=_unwrap_source_governance_package(
            professional_source_governance_package
        )
        if source_package_received
        else None,
        phase=phase,
    )
    target_package = _target_package_from_input(target_review_package)
    target_review = build_mcp_fetch_target_review_preview(
        handoff_package=target_package["handoff_package"],
        handoff_review=target_package["handoff_review"],
        target_review=target_package["target_review"],
        phase=phase,
    )
    alignment = _source_alignment(
        _target_sources(target_package["target_review"]),
        source_governance,
    )
    confirmation_status = {
        "source_governance_reviewed": bool(
            confirmations.get("source_governance_reviewed")
        ),
        "target_review_reviewed": bool(confirmations.get("target_review_reviewed")),
        "all_target_sources_reference_governed_sources": bool(
            confirmations.get("all_target_sources_reference_governed_sources")
        ),
        "no_api_external_fetch": bool(confirmations.get("no_api_external_fetch")),
        "no_database_write": bool(confirmations.get("no_database_write")),
        "no_scheduler_attach": bool(confirmations.get("no_scheduler_attach")),
    }
    gates = [
        {
            "key": "professional_source_governance_package_received",
            "label": "已提供 Professional Source Governance package",
            "passed": source_package_received,
        },
        {
            "key": "professional_source_governance_accepted",
            "label": "來源治理已通過 robots/sitemap/structured-data/public boundary gate",
            "passed": source_governance[
                "mcp_professional_source_governance_accepted"
            ],
        },
        {
            "key": "fetch_target_review_package_received",
            "label": "已提供 MCP Fetch Target Review package",
            "passed": target_package_received,
        },
        {
            "key": "fetch_target_review_accepted",
            "label": "Fetch target review 已通過 adapter/source/rate-limit gate",
            "passed": target_review["mcp_fetch_target_review_accepted"],
        },
        {
            "key": "all_target_sources_governed",
            "label": "每個 fetch target source_key 都已存在於通過治理的 source contract",
            "passed": alignment["all_target_sources_governed"],
        },
        {
            "key": "operator_confirmations_complete",
            "label": "操作員確認治理與 target 已人工覆核，且 API 不連外/不寫 DB/不掛 scheduler",
            "passed": all(confirmation_status.values()),
        },
        {
            "key": "bridge_side_effect_free",
            "label": "本 bridge API 只做交叉審核，不執行 fetch、DB、file、CLI 或 scheduler",
            "passed": True,
        },
    ]
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    accepted = bool(source_package_received and target_package_received and not blocked_reasons)
    return {
        "mode": (
            "mcp_fetch_target_source_governance_review"
            if accepted
            else "mcp_fetch_target_source_governance_review_preview"
        ),
        "phase": phase,
        "source_governance_package_received": source_package_received,
        "target_review_package_received": target_package_received,
        "mcp_fetch_target_source_governance_review_accepted": accepted,
        "ready_for_mcp_fetch_target_review_with_source_governance": accepted,
        "ready_for_manual_fetch_run_package_review": accepted,
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "source_alignment": alignment,
        "operator_confirmation_status": confirmation_status,
        "professional_source_governance": source_governance,
        "mcp_fetch_target_review": target_review,
        "sample_fetch_target_source_governance_review_package": _sample_package(),
        "next_operator_steps": [
            "使用通過治理的 source contract 更新後續 fetch run package。",
            "正式 fetch 仍只能由 operator run command 執行，API 不打外站。",
            "fetch receipt、parser review、candidate handoff 與 queue writer 仍需各自 gate。",
        ],
        "network_request_allowed": False,
        "external_network_executed": False,
        "fetch_executed": False,
        "payload_persisted": False,
        "bridge_review_persisted": False,
        "api_fetches_robots_txt": False,
        "api_fetches_sitemap": False,
        "api_fetches_source_url": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_writes_file": False,
        "api_executes_cli": False,
        "scheduler_attached": False,
    }
