"""End-to-end: import -> publish -> the client's review game -> the admin
results rollup and the Scouting Report, all driven over HTTP."""

from tests.conftest import admin_import_and_publish, as_user


def test_full_review_and_results_flow(client, seed):
    # --- admin: import three options and publish all of them ---------------
    as_user(client, "t_admin")
    options = [{"slug": "alpha"}, {"slug": "beta"}, {"slug": "gamma"}]
    ids = admin_import_and_publish(client, seed.project, options)
    assert set(ids) == {"alpha", "beta", "gamma"}
    published_ids = set(ids.values())

    listing = client.get(f"/api/projects/{seed.project.id}/options").json()
    labels = {row["slug"]: row["display_label"] for row in listing}

    # --- member: the bundle sees exactly the published set, in a stable order
    as_user(client, "t_member")
    bundle_1 = client.get(f"/api/projects/{seed.project.id}/review").json()
    order_1 = [o["id"] for o in bundle_1["options"]]
    assert set(order_1) == published_ids

    bundle_2 = client.get(f"/api/projects/{seed.project.id}/review").json()
    order_2 = [o["id"] for o in bundle_2["options"]]
    assert order_2 == order_1

    # --- member: rate all three, note on alpha, aspect votes on two ---------
    rate_alpha = client.patch(
        f"/api/projects/{seed.project.id}/review/options/{ids['alpha']}",
        json={"rating": 3, "note": "love this one"},
    )
    assert rate_alpha.status_code == 200

    rate_beta = client.patch(
        f"/api/projects/{seed.project.id}/review/options/{ids['beta']}", json={"rating": 2}
    )
    assert rate_beta.status_code == 200

    rate_gamma = client.patch(
        f"/api/projects/{seed.project.id}/review/options/{ids['gamma']}", json={"rating": 0}
    )
    assert rate_gamma.status_code == 200

    vote_alpha = client.put(
        f"/api/projects/{seed.project.id}/review/options/{ids['alpha']}/aspects/colours",
        json={"vote": 1},
    )
    assert vote_alpha.status_code == 200

    vote_beta = client.put(
        f"/api/projects/{seed.project.id}/review/options/{ids['beta']}/aspects/typography",
        json={"vote": -1},
    )
    assert vote_beta.status_code == 200

    # --- member: final pick on the top-rated option, closing note, finish ---
    final_pick = client.put(
        f"/api/projects/{seed.project.id}/review/final-pick",
        json={
            "option_id": ids["alpha"],
            "closing_note": "go with alpha",
            "completed": True,
        },
    )
    assert final_pick.status_code == 200
    assert final_pick.json()["completed_at"] is not None

    # --- admin: the results rollup --------------------------------------
    as_user(client, "t_admin")
    results = client.get(f"/api/projects/{seed.project.id}/results")
    assert results.status_code == 200
    results_body = results.json()

    reviewer = next(r for r in results_body["reviewers"] if r["username"] == "t_member")
    assert reviewer["rated_count"] == 3
    assert reviewer["total_published"] == 3
    assert reviewer["completed_at"] is not None
    assert reviewer["has_final_pick"] is True

    alpha_result = next(
        o for o in results_body["options"] if o["option"]["id"] == ids["alpha"]
    )
    assert alpha_result["final_pick_count"] == 1
    assert alpha_result["distribution"] == {"0": 0, "1": 0, "2": 0, "3": 1}
    assert alpha_result["mean"] == 3
    note_row = next(r for r in alpha_result["ratings"] if r["username"] == "t_member")
    assert note_row["note"] == "love this one"

    beta_result = next(o for o in results_body["options"] if o["option"]["id"] == ids["beta"])
    assert beta_result["distribution"] == {"0": 0, "1": 0, "2": 1, "3": 0}

    gamma_result = next(
        o for o in results_body["options"] if o["option"]["id"] == ids["gamma"]
    )
    assert gamma_result["distribution"] == {"0": 1, "1": 0, "2": 0, "3": 0}

    # --- admin: the Scouting Report markdown --------------------------------
    report = client.get(f"/api/projects/{seed.project.id}/report")
    assert report.status_code == 200
    assert "text/markdown" in report.headers["content-type"]
    report_text = report.text
    assert labels["alpha"] in report_text
    assert "love this one" in report_text
    assert "go with alpha" in report_text
