import json
import subprocess
import sys
from datetime import datetime, timezone


def _identity_candidate(platform, manifest_id, index):
    return {
        "candidate_id": f"{platform}:{manifest_id}:{index}",
        "candidate_index": index,
        "field_contract_count": 14,
        "identity_fingerprint": f"identity-{platform}-{index}",
        "identity_key_fields": ["platform", "platform_product_id", "title", "url"],
        "match_strategy": "deterministic_contract_replay_no_values",
        "price_write_blocked_until_promotion_gate": True,
        "ready_for_price_table_write": False,
        "ready_for_promotion_gate_replay": True,
        "requires_evidence_time": True,
        "requires_platform_scope": True,
        "requires_product_id_or_url_identity": True,
        "requires_title_url_cross_check": True,
    }


def _write_identity_matcher_receipt(
    root,
    *,
    platform="coupang_tw",
    manifest_id="coupang-403",
    adapter_code="coupang",
    barrier_type="access_denied",
    capture_runtime_unavailable=False,
):
    receipt_dir = root / platform / manifest_id
    receipt_dir.mkdir(parents=True)
    source_root = "runtime_artifacts"
    payload = {
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "policy": "controlled_pixelrag_marketplace_identity_matcher_replay_v1",
        "worker_status": "executed_marketplace_identity_matcher_replay_ready",
        "platform": platform,
        "manifest_id": manifest_id,
        "adapter_code": adapter_code,
        "identity_matcher_receipt_path": (
            f"{source_root}/pixelrag_marketplace_identity_matcher_replay_receipts/"
            f"{platform}/{manifest_id}/marketplace_identity_matcher_replay_receipt.json"
        ),
        "adapter_dry_run_receipt_path": (
            f"{source_root}/pixelrag_marketplace_adapter_dry_run_receipts/"
            f"{platform}/{manifest_id}/marketplace_adapter_dry_run_receipt.json"
        ),
        "adapter_preflight_receipt_path": (
            f"{source_root}/pixelrag_marketplace_adapter_preflight_receipts/"
            f"{platform}/{manifest_id}/marketplace_adapter_preflight_receipt.json"
        ),
        "source_contract_replay_receipt_path": (
            f"{source_root}/pixelrag_source_contract_replay_receipts/"
            f"{platform}/{manifest_id}/source_contract_replay_receipt.json"
        ),
        "source_worker_receipt_path": (
            f"{source_root}/pixelrag_platform_probe_worker_receipts/"
            f"{platform}/{manifest_id}/platform_probe_worker_receipt.json"
        ),
        "source_receipt_path": (
            f"{source_root}/pixelrag_visual_evidence/"
            f"{platform}/{manifest_id}/capture_receipt.json"
        ),
        "identity_matcher_replay_check_count": 20,
        "identity_matcher_replay_check_pass_count": 20,
        "identity_matcher_replay_checks": {
            "adapter_dry_run_checks_all_passed": True,
            "adapter_dry_run_ready": True,
            "adapter_dry_run_version_supported": True,
            "blocked_page_not_product_data": True,
            "database_write_disallowed": True,
            "direct_ai_insights_write_disallowed": True,
            "direct_price_write_disallowed": True,
            "identity_candidate_contracts_generated": True,
            "identity_candidate_count_matches_offer_count": True,
            "identity_gate_required": True,
            "identity_key_fields_present": True,
            "model_call_disallowed": True,
            "network_call_disallowed": True,
            "offer_candidate_contracts_present": True,
            "price_write_blocked_until_promotion_gate": True,
            "promotion_gate_replay_ready": True,
            "promotion_gates_required": True,
            "receipt_fresh": True,
            "receipt_parse_ok": True,
            "source_provenance_paths_present": True,
        },
        "identity_matcher_replay": {
            "identity_matcher_replay_version": "pixelrag_marketplace_identity_matcher_replay_v1",
            "adapter_dry_run_version": "pixelrag_marketplace_adapter_dry_run_v1",
            "adapter_preflight_version": "pixelrag_marketplace_adapter_preflight_v1",
            "source_contract_version": "pixelrag_marketplace_source_contract_v1",
            "contract_id": f"{platform}:{manifest_id}:{adapter_code}",
            "adapter_code": adapter_code,
            "barrier_type": barrier_type,
            "capture_runtime_unavailable": capture_runtime_unavailable,
            "input_adapter_dry_run_receipt_path": (
                f"{source_root}/pixelrag_marketplace_adapter_dry_run_receipts/"
                f"{platform}/{manifest_id}/marketplace_adapter_dry_run_receipt.json"
            ),
            "adapter_preflight_receipt_path": (
                f"{source_root}/pixelrag_marketplace_adapter_preflight_receipts/"
                f"{platform}/{manifest_id}/marketplace_adapter_preflight_receipt.json"
            ),
            "source_contract_replay_receipt_path": (
                f"{source_root}/pixelrag_source_contract_replay_receipts/"
                f"{platform}/{manifest_id}/source_contract_replay_receipt.json"
            ),
            "source_worker_receipt_path": (
                f"{source_root}/pixelrag_platform_probe_worker_receipts/"
                f"{platform}/{manifest_id}/platform_probe_worker_receipt.json"
            ),
            "source_receipt_path": (
                f"{source_root}/pixelrag_visual_evidence/"
                f"{platform}/{manifest_id}/capture_receipt.json"
            ),
            "identity_match_execution_mode": "deterministic_replay_only_no_network_no_db",
            "identity_key_fields": ["platform", "platform_product_id", "title", "url"],
            "identity_candidate_count": 2,
            "identity_candidate_contracts": [
                _identity_candidate(platform, manifest_id, 0),
                _identity_candidate(platform, manifest_id, 1),
            ],
            "required_before_data_promotion": [
                "public_source_boundary",
                "rate_limit_contract",
                "provenance_contract",
                "identity_matcher_replay",
                "promotion_gate",
                "embedding_signature_guard",
            ],
            "allowed_next_step": "run_marketplace_promotion_gate_replay",
        },
        "promotion_boundary": {
            "direct_ai_insights_write_allowed": False,
            "direct_price_write_allowed": False,
        },
        "writes_database": False,
        "writes_database_count": 0,
        "network_call_performed": False,
        "model_call_performed": False,
    }
    path = receipt_dir / "marketplace_identity_matcher_replay_receipt.json"
    path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
    return path


def test_marketplace_promotion_gate_replay_reads_identity_receipts(tmp_path):
    from services.pixelrag_marketplace_promotion_gate_replay_service import (
        POLICY,
        run_pixelrag_marketplace_promotion_gate_replay,
    )

    identity_root = tmp_path / "identity_matcher"
    _write_identity_matcher_receipt(identity_root)
    _write_identity_matcher_receipt(
        identity_root,
        platform="shopee_tw",
        manifest_id="shopee-runtime-gap",
        adapter_code="shopee",
        barrier_type="language_or_region_interstitial",
        capture_runtime_unavailable=True,
    )

    payload = run_pixelrag_marketplace_promotion_gate_replay(
        identity_matcher_receipt_root=identity_root,
        platform=("coupang_tw", "shopee_tw"),
    )
    by_platform = {item["platform"]: item for item in payload["worker_items"]}

    assert payload["policy"] == POLICY
    assert payload["status"] == "ok"
    assert payload["summary"]["candidate_count"] == 2
    assert payload["summary"]["ready_count"] == 2
    assert payload["summary"]["dry_run_count"] == 2
    assert payload["summary"]["promotion_candidate_count"] == 4
    assert payload["summary"]["embedding_signature_guard_ready_count"] == 4
    assert payload["summary"]["capture_runtime_gap_count"] == 1
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["controlled_apply"]["network_call"] is False
    assert payload["controlled_apply"]["writes_database"] is False
    assert payload["promotion_boundary"]["writes_price_tables"] is False
    assert payload["next_machine_action"] == "run_marketplace_promotion_gate_replay_execute"
    assert by_platform["coupang_tw"]["worker_status"] == (
        "dry_run_ready_for_marketplace_promotion_gate_replay"
    )
    first_promotion = by_platform["coupang_tw"]["promotion_gate_replay"][
        "promotion_candidate_contracts"
    ][0]
    assert first_promotion["ready_for_embedding_signature_guard_replay"] is True
    assert first_promotion["ready_for_candidate_knowledge_replay"] is True
    assert first_promotion["ready_for_price_table_write"] is False
    assert (
        first_promotion["price_write_blocked_until_embedding_signature_guard"] is True
    )
    assert by_platform["shopee_tw"]["promotion_gate_replay"][
        "capture_runtime_unavailable"
    ] is True


def test_marketplace_promotion_gate_replay_execute_writes_receipt(tmp_path):
    from services.pixelrag_marketplace_promotion_gate_replay_service import (
        run_pixelrag_marketplace_promotion_gate_replay,
    )

    identity_root = tmp_path / "identity_matcher"
    output_root = tmp_path / "promotion_gate"
    _write_identity_matcher_receipt(identity_root)

    payload = run_pixelrag_marketplace_promotion_gate_replay(
        identity_matcher_receipt_root=identity_root,
        output_root=output_root,
        platform="coupang_tw",
        execute=True,
        write_receipt=True,
    )

    assert payload["status"] == "ok"
    assert payload["summary"]["executed_count"] == 1
    assert payload["summary"]["receipt_written_count"] == 1
    assert payload["controlled_apply"]["artifact_write"] is True
    assert payload["controlled_apply"]["writes_database"] is False
    assert payload["next_machine_action"] == "run_marketplace_embedding_signature_guard_replay"
    receipt_path = (
        output_root
        / "coupang_tw"
        / "coupang-403"
        / "marketplace_promotion_gate_replay_receipt.json"
    )
    assert receipt_path.exists()
    receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
    assert receipt["worker_status"] == "executed_marketplace_promotion_gate_replay_ready"
    assert receipt["artifact_write_performed"] is True
    assert receipt["writes_database"] is False
    assert receipt["promotion_gate_replay_check_pass_count"] == (
        receipt["promotion_gate_replay_check_count"]
    )
    assert receipt["promotion_gate_replay"]["allowed_next_step"] == (
        "run_marketplace_embedding_signature_guard_replay"
    )


def test_marketplace_promotion_gate_replay_cli_outputs_json(tmp_path):
    identity_root = tmp_path / "identity_matcher"
    _write_identity_matcher_receipt(identity_root)

    completed = subprocess.run(
        [
            sys.executable,
            "scripts/ops/run_pixelrag_marketplace_promotion_gate_replay.py",
            "--identity-matcher-receipt-root",
            str(identity_root),
            "--platform",
            "coupang_tw",
        ],
        capture_output=True,
        check=False,
        text=True,
    )

    assert completed.returncode == 0
    payload = json.loads(completed.stdout)
    assert payload["summary"]["candidate_count"] == 1
    assert payload["summary"]["ready_count"] == 1
    assert payload["summary"]["promotion_candidate_count"] == 2
    assert payload["controlled_apply"]["writes_database"] is False


def test_marketplace_promotion_gate_replay_route_returns_readback(
    tmp_path,
    monkeypatch,
):
    from flask import Flask
    from routes import system_public_routes as routes
    from services import pixelrag_marketplace_promotion_gate_replay_service as service

    identity_root = tmp_path / "identity_matcher"
    _write_identity_matcher_receipt(identity_root)
    monkeypatch.setattr(
        service,
        "DEFAULT_IDENTITY_MATCHER_RECEIPT_ROOT",
        str(identity_root),
    )

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai-automation/pixelrag-marketplace-promotion-gate-replay?platform=coupang_tw"
    ):
        response = (
            routes
            .ai_automation_pixelrag_marketplace_promotion_gate_replay_api
            .__wrapped__()
        )
    payload = response.get_json()

    assert payload["policy"] == (
        "controlled_pixelrag_marketplace_promotion_gate_replay_v1"
    )
    assert payload["summary"]["candidate_count"] == 1
    assert payload["summary"]["ready_count"] == 1
    assert payload["controlled_apply"]["writes_database"] is False
