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


def _write_receipt(root, *, platform, manifest_id, title, url, http_status=200):
    receipt_dir = root / platform / manifest_id
    tiles_dir = receipt_dir / "tiles"
    tiles_dir.mkdir(parents=True)
    screenshot = receipt_dir / "screenshot.png"
    screenshot.write_bytes(b"png")
    files = [{"kind": "screenshot", "path": str(screenshot)}]
    for index in range(4):
        tile = tiles_dir / f"tile-{index}.png"
        tile.write_bytes(b"tile")
        files.append({"kind": "tile", "path": str(tile)})
    receipt = {
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "status": "captured",
        "manifest_id": manifest_id,
        "http_status": http_status,
        "capture_target": {
            "platform": platform,
            "url": url,
            "crawler": "PixelRAGMarketplaceSearch.visual_fallback",
        },
        "page_metrics": {
            "title": title,
            "final_url": url,
        },
        "tile_plan": {
            "planned_tile_count": 4,
            "emitted_tile_count": 4,
        },
        "files": files,
    }
    path = receipt_dir / "capture_receipt.json"
    path.write_text(json.dumps(receipt, ensure_ascii=False), encoding="utf-8")
    return path


def test_pixelrag_ocr_vlm_replay_contract_splits_ready_and_blocked_receipts(tmp_path):
    from services.pixelrag_ocr_vlm_replay_service import (
        POLICY,
        build_pixelrag_ocr_vlm_replay_contract,
    )

    _write_receipt(
        tmp_path,
        platform="shopee_tw",
        manifest_id="shopee-ok",
        title="Shopee 防曬乳",
        url="https://shopee.tw/search?keyword=%E9%98%B2%E6%9B%AC%E4%B9%B3",
    )
    _write_receipt(
        tmp_path,
        platform="coupang_tw",
        manifest_id="coupang-403",
        title="Access Denied",
        url="https://www.tw.coupang.com/search?q=iphone",
        http_status=403,
    )

    payload = build_pixelrag_ocr_vlm_replay_contract(artifact_root=tmp_path)
    by_platform = {item["platform"]: item for item in payload["replay_items"]}

    assert payload["policy"] == POLICY
    assert payload["status"] == "warning"
    assert payload["summary"]["receipt_count"] == 2
    assert payload["summary"]["replay_ready_count"] == 1
    assert payload["summary"]["blocked_count"] == 1
    assert payload["summary"]["extraction_execution_performed"] is False
    assert by_platform["shopee_tw"]["replay_status"] == "ready_for_ocr_vlm_replay"
    assert by_platform["shopee_tw"]["ready_for_ollama_vlm_worker"] is True
    assert len(by_platform["shopee_tw"]["input_tiles"]) == 4
    assert "price" in {
        field["field"] for field in by_platform["shopee_tw"]["field_contract"]
    }
    assert by_platform["coupang_tw"]["replay_status"] == "blocked"
    assert by_platform["coupang_tw"]["next_machine_action"] == (
        "run_platform_probe_or_use_structured_api"
    )
    assert payload["model_route_contract"]["hosted_vlm_api_allowed"] is False
    assert payload["replay_contract"]["writes_price_tables"] is False
    assert payload["controlled_apply"]["primary_human_gate_count"] == 0


def test_pixelrag_ocr_vlm_replay_cli_outputs_machine_readable_json(tmp_path):
    _write_receipt(
        tmp_path,
        platform="shopee_tw",
        manifest_id="shopee-ok",
        title="Shopee 防曬乳",
        url="https://shopee.tw/search?keyword=sunscreen",
    )

    completed = subprocess.run(
        [
            sys.executable,
            "scripts/ops/report_pixelrag_ocr_vlm_replay.py",
            "--artifact-root",
            str(tmp_path),
            "--platform",
            "shopee_tw",
        ],
        capture_output=True,
        check=False,
        text=True,
    )

    assert completed.returncode == 0
    payload = json.loads(completed.stdout)
    assert payload["summary"]["receipt_count"] == 1
    assert payload["summary"]["replay_ready_count"] == 1
    assert payload["replay_items"][0]["platform"] == "shopee_tw"
    assert payload["replay_items"][0]["automation_boundary"]["vlm_execution_performed"] is False


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

    _write_receipt(
        tmp_path,
        platform="shopee_tw",
        manifest_id="shopee-ok",
        title="Shopee 防曬乳",
        url="https://shopee.tw/search?keyword=sunscreen",
    )
    monkeypatch.setattr(service, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai-automation/pixelrag-ocr-vlm-replay?platform=shopee_tw"
    ):
        response = routes.ai_automation_pixelrag_ocr_vlm_replay_api.__wrapped__()
    payload = response.get_json()

    assert payload["policy"] == "read_only_pixelrag_ocr_vlm_replay_contract_v1"
    assert payload["summary"]["receipt_count"] == 1
    assert payload["summary"]["replay_ready_count"] == 1
    assert payload["replay_contract"]["writes_database"] is False
