"""End-to-end build workflow — the flows Mike cares about most: assemble a
build, then verify the chip, the /build page, and the public /b/<code>
page all show what we'd expect. These are the regression guards for the
exact class of bug we keep hitting (the "()" / wrong-count header chip).

All hit the dev mirror DB; marked db/integration so they skip when it's
down. Anonymous builds created here are torn down via the track_codes
fixture.
"""
import re

import pytest

from conftest import add_part

pytestmark = [pytest.mark.integration, pytest.mark.db]


# --------------------------------------------------------------------------- #
# Helpers — read the global header chip (partials/build_chip.html) out of a
# rendered page. The chip is `id="build-chip" ... display_name ... (count)`.
# --------------------------------------------------------------------------- #
def _chip_region(html):
    m = re.search(r'id="build-chip".*?</div>\s*</div>', html, re.S)
    return m.group(0) if m else ""


def _chip_count(html):
    region = _chip_region(html)
    m = re.search(r"\((\d+)\)", region)
    return int(m.group(1)) if m else None


# --------------------------------------------------------------------------- #
# Adding to the working build
# --------------------------------------------------------------------------- #
def test_fresh_session_chip_is_empty_named_build(client, db_conn):
    html = client.get("/").get_data(as_text=True)
    region = _chip_region(html)
    assert region, "build chip should render on every page"
    assert "Build #1" in region          # display_name present, never blank
    assert _chip_count(html) == 0        # empty draft shows (0), not ()


def test_add_one_part_updates_chip_and_build_page(client, db_conn, sample_parts):
    pid = sample_parts[0]["id"]
    add_part(client, pid)

    # Chip on any page reflects the active draft.
    home = client.get("/").get_data(as_text=True)
    assert _chip_count(home) == 1
    assert "Build #1" in _chip_region(home)   # NOT "()" — name still there

    # The /build page lists the item and the count header.
    build = client.get("/build").get_data(as_text=True)
    assert "Your parts (1)" in build
    # the part's description should appear on the page
    desc = (sample_parts[0]["description"] or "")[:30]
    if desc:
        assert desc in build


def test_add_multiple_quantities(client, db_conn, sample_parts):
    pid = sample_parts[0]["id"]
    add_part(client, pid, qty=3)
    home = client.get("/").get_data(as_text=True)
    assert _chip_count(home) == 3


def test_add_two_distinct_parts(client, db_conn, sample_parts):
    add_part(client, sample_parts[0]["id"])
    add_part(client, sample_parts[1]["id"])
    build = client.get("/build").get_data(as_text=True)
    assert "Your parts (2)" in build


def test_remove_and_clear(client, db_conn, sample_parts):
    pid = sample_parts[0]["id"]
    add_part(client, pid, qty=2)
    client.post("/build/remove", data={"id": pid})
    assert _chip_count(client.get("/").get_data(as_text=True)) == 0


# --------------------------------------------------------------------------- #
# Saving an anonymous build + viewing it
# --------------------------------------------------------------------------- #
def _save_anonymous(client, sample_parts, track_codes, title="Pytest Build"):
    add_part(client, sample_parts[0]["id"])
    add_part(client, sample_parts[1]["id"])
    resp = client.post("/build/save",
                       data={"title": title, "anonymous": "1"})
    assert resp.status_code == 302
    loc = resp.headers["Location"]
    assert loc.startswith("/b/"), f"expected /b/<code> redirect, got {loc}"
    code = loc.rsplit("/", 1)[-1].split("?")[0]
    track_codes.append(code)
    return code


def test_anonymous_save_creates_viewable_build(client, db_conn,
                                               sample_parts, track_codes):
    code = _save_anonymous(client, sample_parts, track_codes,
                           title="My Slim Build")
    page = client.get(f"/b/{code}", follow_redirects=True).get_data(as_text=True)
    assert page                                   # renders
    # title surfaces in the page (h1 / og)
    assert "My Slim Build" in page or "Slim Build" in page
    # both items are present
    desc0 = (sample_parts[0]["description"] or "")[:25]
    if desc0:
        assert desc0 in page


def test_saved_build_persists_to_db(client, db_conn, sample_parts, track_codes):
    code = _save_anonymous(client, sample_parts, track_codes)
    with db_conn.cursor() as cur:
        cur.execute("SELECT id, owner_user_id, title FROM build WHERE code=%s",
                    (code,))
        row = cur.fetchone()
        assert row is not None
        assert row["owner_user_id"] is None       # anonymous
        cur.execute("SELECT COUNT(*) AS n FROM build_item WHERE build_id=%s",
                    (row["id"],))
        assert cur.fetchone()["n"] == 2


def test_save_resets_active_draft(client, db_conn, sample_parts, track_codes):
    # After save the working slot is freed for new work (count back to 0).
    _save_anonymous(client, sample_parts, track_codes)
    assert _chip_count(client.get("/").get_data(as_text=True)) == 0


# --------------------------------------------------------------------------- #
# THE regression guard: viewing a saved /b/<code> must NOT clobber the
# global chip (which reflects the ACTIVE DRAFT, a different thing). This is
# the "()" bug we shipped + fixed — pin it so it can't come back.
# --------------------------------------------------------------------------- #
def test_viewing_public_build_does_not_clobber_chip(client, db_conn,
                                                    sample_parts, track_codes):
    # 1. Save a build (this empties the active draft).
    code = _save_anonymous(client, sample_parts, track_codes)
    # 2. Start NEW work in the freed draft so the chip has a live count.
    add_part(client, sample_parts[0]["id"])
    before = client.get("/").get_data(as_text=True)
    assert _chip_count(before) == 1
    assert "Build #" in _chip_region(before)

    # 3. View the OTHER saved build. The chip must still show the active
    #    draft's count + name — NOT "()" and NOT the viewed build's items.
    page = client.get(f"/b/{code}", follow_redirects=True).get_data(as_text=True)
    region = _chip_region(page)
    assert region, "chip should still render on the public build page"
    assert _chip_count(page) == 1, "chip count clobbered by public_view (the () bug)"
    assert "Build #" in region, "chip name blanked by public_view (the () bug)"


# --------------------------------------------------------------------------- #
# Multiple drafts
# --------------------------------------------------------------------------- #
def test_new_draft_and_switch(client, db_conn, sample_parts):
    add_part(client, sample_parts[0]["id"])         # Build #1 has 1 item
    client.post("/build/draft/new")                 # -> Build #2 (active, empty)
    assert _chip_count(client.get("/").get_data(as_text=True)) == 0
