import json
import subprocess
import sys


def test_pixelrag_application_portfolio_prioritizes_commerce_and_guardrails():
    from services.pixelrag_application_portfolio_service import (
        POLICY,
        build_pixelrag_application_portfolio,
    )

    payload = build_pixelrag_application_portfolio(include_forbidden=True)
    lanes = {item["id"]: item for item in payload["lanes"]}

    assert payload["policy"] == POLICY
    assert payload["status"] == "portfolio_ready"
    assert payload["summary"]["lane_count"] >= 10
    assert payload["summary"]["worker_required_count"] >= 1
    assert "commerce.marketplace_visual_offer_cards" in lanes
    assert lanes["commerce.marketplace_visual_offer_cards"]["priority"] == "P0"
    assert lanes["commerce.marketplace_visual_offer_cards"]["next_machine_action"] == (
        "run_ollama_first_vlm_replay_worker"
    )
    assert "Google Merchant product data" in lanes[
        "commerce.product_feed_and_structured_data_gap_check"
    ]["integrates_with"]
    assert lanes["commerce.platform_barrier_classifier"]["status"] == (
        "production_contract_ready"
    )
    assert lanes["forbidden.personalized_or_private_state"]["status"] == "forbidden"
    assert payload["controlled_apply"]["db_write"] is False
    assert payload["controlled_apply"]["primary_human_gate_count"] == 0
    assert any(item["id"] == "pixelrag_visual_rag_pattern" for item in payload["source_basis"])
    assert payload["recommended_order"][0]["priority"] == "P0"


def test_pixelrag_application_portfolio_filters_area_without_forbidden_by_default():
    from services.pixelrag_application_portfolio_service import build_pixelrag_application_portfolio

    payload = build_pixelrag_application_portfolio(area="governance")

    assert {item["area"] for item in payload["lanes"]} == {"governance"}
    assert all(item["status"] != "forbidden" for item in payload["lanes"])
    assert payload["summary"]["lane_count"] == 1
    assert payload["lanes"][0]["id"] == "commerce.platform_barrier_classifier"


def test_pixelrag_application_portfolio_cli_outputs_machine_readable_json():
    completed = subprocess.run(
        [
            sys.executable,
            "scripts/ops/report_pixelrag_application_portfolio.py",
            "--area",
            "commerce",
            "--priority",
            "P1",
        ],
        capture_output=True,
        check=False,
        text=True,
    )

    assert completed.returncode == 0
    payload = json.loads(completed.stdout)
    assert payload["success"] is True
    assert payload["filters"]["area"] == "commerce"
    assert payload["filters"]["priority"] == "P1"
    assert {item["priority"] for item in payload["lanes"]} == {"P1"}
    assert payload["controlled_apply"]["network_call"] is False


def test_pixelrag_application_portfolio_route_returns_readback():
    from flask import Flask
    from routes import system_public_routes as routes

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai-automation/pixelrag-application-portfolio?area=rag"
    ):
        response = routes.ai_automation_pixelrag_application_portfolio_api.__wrapped__()
    payload = response.get_json()

    assert payload["policy"] == "read_only_pixelrag_application_portfolio_v1"
    assert payload["filters"]["area"] == "rag"
    assert {item["area"] for item in payload["lanes"]} == {"rag"}
    assert payload["next_machine_action"] == "run_ollama_first_vlm_replay_worker"
