import json

from tools.build_static import build_static


def test_build_emits_frontend_baked_json_and_only_referenced_media(tmp_path):
    out = tmp_path / "dist"
    media = tmp_path / "media"
    result = build_static(
        out, media,
        media_base="https://static.benstull.art/",
        app_path="/human-experience-simulator",
    )
    app_dir = out / "human-experience-simulator"

    # frontend present under the app path; dev/author surfaces excluded
    assert (app_dir / "index.html").exists()
    assert (app_dir / "app.js").exists()
    assert (app_dir / "scrub.js").exists()
    assert (app_dir / "alteration.js").exists()
    assert (app_dir / "config.js").exists()
    # Credits/colophon ships so CC-BY / CC-BY-SA attribution is reachable from the public site.
    assert (app_dir / "credits.html").exists()
    assert (app_dir / "credits.js").exists()
    assert not (app_dir / "author.html").exists()
    assert not list(app_dir.glob("review*.html"))

    # apex + no-slash redirect rules
    redirects = (out / "_redirects").read_text()
    assert "/  /human-experience-simulator/  308" in redirects
    assert "/human-experience-simulator  /human-experience-simulator/  308" in redirects

    # baked JSON matches the API shape
    clips = json.loads((app_dir / "clips.json").read_text())
    assert "clips" in clips and clips["clips"]
    ring = json.loads((app_dir / "ring.json").read_text())
    assert "scales" in ring and "transitions" in ring
    assert all("audio" in s for s in ring["scales"])           # needed by client alteration
    versions = json.loads((app_dir / "media-versions.json").read_text())
    assert "versions" in versions

    # config.js points at R2 + static mode
    cfg = (app_dir / "config.js").read_text()
    assert "https://static.benstull.art/" in cfg and "static: true" in cfg

    # media tree holds ONLY referenced files — no masters/mezzanines
    synced = {p.name for p in media.rglob("*.mp4")}
    assert synced, "expected synced media"
    assert not any(n in ("master.mp4", "mezzanine.mp4") for n in synced)
    # every versioned file exists in the media tree
    for f in versions["versions"]:
        assert (media / f).exists(), f"missing synced media: {f}"
    assert result["media_files"] == sum(1 for _ in media.rglob("*") if _.is_file())
