"""Form test scenarios: saved with the form, run through the real submission
checks from the designer's endpoint and the CI script, never saving data."""

import subprocess
import sys
from pathlib import Path

from tests.test_line_items import FIELDS

SCENARIOS = [
    {"name": "Discounted order", "values": {"discount": 10, "items": [{"product": "Pen", "qty": 2, "price": 10}]}, "expect_values": {"total": 18}},
    {"name": "Needs a product", "values": {"items": [{"qty": 1}]}, "expect_valid": False, "expect_errors": {"items": "product is required"}},
    {"name": "Wrong expectation", "values": {"discount": 0, "items": [{"product": "Pen", "qty": 1, "price": 5}]}, "expect_values": {"total": 6}},
    {"name": "Expects a refusal", "values": {"items": [{"product": "Pen"}]}, "expect_valid": False},
]


async def test_run_from_the_designer(client, auth_headers):
    resp = await client.post("/forms/test-scenarios/run", headers=auth_headers, json={"field_definitions": FIELDS, "scenarios": SCENARIOS})
    assert resp.status_code == 200, resp.text
    results = {r["name"]: r for r in resp.json()}
    assert results["Discounted order"]["passed"] and results["Discounted order"]["values"]["total"] == 18
    assert results["Needs a product"]["passed"]
    assert not results["Wrong expectation"]["passed"]
    assert results["Wrong expectation"]["failures"] == ["Total: expected 6, got 5."]
    assert not results["Expects a refusal"]["passed"]
    assert "accepted" in results["Expects a refusal"]["failures"][0]
    # Nothing was stored.
    assert (await client.get("/forms", headers=auth_headers)).json() == []


async def test_saved_with_the_form_and_run_by_the_ci_script(client, auth_headers, test_tenant):
    created = await client.post("/forms", headers=auth_headers, json={"name": "Order", "field_definitions": FIELDS, "settings": {"test_scenarios": SCENARIOS[:2]}})
    assert created.status_code == 201, created.text
    assert [s["name"] for s in created.json()["settings"]["test_scenarios"]] == ["Discounted order", "Needs a product"]

    script = Path(__file__).resolve().parents[1] / "scripts" / "run_form_scenarios.py"
    ok = subprocess.run([sys.executable, str(script), "--tenant", str(test_tenant["tenant_id"])], capture_output=True, text=True, timeout=120)
    assert ok.returncode == 0, ok.stdout + ok.stderr
    assert "2 passed, 0 failed." in ok.stdout

    form_id = created.json()["form_id"]
    await client.patch(f"/forms/{form_id}", headers=auth_headers, json={"settings": {"test_scenarios": SCENARIOS[2:3]}})
    bad = subprocess.run([sys.executable, str(script), "--tenant", str(test_tenant["tenant_id"]), "--quiet"], capture_output=True, text=True, timeout=120)
    assert bad.returncode == 1
    assert "FAIL" in bad.stdout and "Total: expected 6, got 5." in bad.stdout
