import pytest
from pathlib import Path
from datetime import UTC, datetime

from l4d2web.app import create_app
from l4d2web.auth import hash_password
from l4d2web.db import init_db, session_scope
from l4d2web.models import Blueprint, BlueprintOverlay, Job, JobLog, Overlay, Server, User


@pytest.fixture
def auth_client_with_server(tmp_path, monkeypatch):
    db_url = f"sqlite:///{tmp_path/'pages.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        user = User(username="alice", password_digest=hash_password("secret"), admin=False)
        session.add(user)
        session.flush()

        blueprint = Blueprint(user_id=user.id, name="default", arguments="[]", config="[]")
        session.add(blueprint)
        session.flush()

        overlay = Overlay(name="standard", path="/opt/l4d2/overlays/standard")
        session.add(overlay)
        session.flush()

        session.add(BlueprintOverlay(blueprint_id=blueprint.id, overlay_id=overlay.id, position=0))
        session.add(Server(user_id=user.id, blueprint_id=blueprint.id, name="alpha", port=27015))
        session.flush()
        user_id = user.id

    client = app.test_client()
    with client.session_transaction() as sess:
        sess["user_id"] = user_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()
    return client


@pytest.fixture
def user_client_and_other_blueprint(tmp_path, monkeypatch):
    db_url = f"sqlite:///{tmp_path/'otherbp.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        owner = User(username="owner", password_digest=hash_password("secret"), admin=False)
        other = User(username="other", password_digest=hash_password("secret"), admin=False)
        session.add_all([owner, other])
        session.flush()

        blueprint = Blueprint(user_id=other.id, name="private", arguments="[]", config="[]")
        session.add(blueprint)
        session.flush()

        owner_id = owner.id
        blueprint_id = blueprint.id

    client = app.test_client()
    with client.session_transaction() as sess:
        sess["user_id"] = owner_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    return client, blueprint_id


def test_dashboard_is_simple_landing_page(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/dashboard")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Dashboard" in text
    assert "Use the navigation to manage servers, blueprints, and overlays." in text
    assert "alpha" not in text


def test_shell_nav_uses_main_sections(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/dashboard")
    text = response.get_data(as_text=True)

    assert 'href="/dashboard"' in text
    assert 'href="/servers"' in text
    assert 'href="/blueprints"' in text
    assert 'href="/overlays"' in text
    assert 'action="/logout"' in text
    assert "csrf_token" in text


def test_css_tokens_define_neutral_light_and_dark_theme() -> None:
    css = (Path(__file__).resolve().parents[1] / "l4d2web" / "static" / "css" / "tokens.css").read_text()

    for token in [
        "--color-bg",
        "--color-surface",
        "--color-text",
        "--color-muted",
        "--color-border",
        "--color-link",
        "--space-base",
        "--space-xs",
        "--space-s",
        "--space-m",
        "--space-l",
        "--space-xl",
        "--space-2xl",
        "--radius-s",
        "--radius-m",
        "--line",
    ]:
        assert token in css
    assert "prefers-color-scheme: dark" in css
    assert "radial-gradient" not in (Path(__file__).resolve().parents[1] / "l4d2web" / "static" / "css" / "layout.css").read_text()


def test_log_tokens_follow_light_and_dark_theme() -> None:
    css = (Path(__file__).resolve().parents[1] / "l4d2web" / "static" / "css" / "tokens.css").read_text()

    assert "--color-log-bg: #f8fafc;" in css
    assert "--color-log-text: #18181b;" in css
    dark_theme = css.split("@media (prefers-color-scheme: dark)", 1)[1]
    assert "--color-log-bg: #111827;" in dark_theme
    assert "--color-log-text: #e5e7eb;" in dark_theme


def test_server_detail_shows_operations_and_logs(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/servers/1")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Server: alpha" in text
    # Default actual_state is "unknown", no active job → only `start` and modal `delete`.
    assert 'action="/servers/1/start"' in text
    assert 'action="/servers/1/stop"' not in text
    assert 'action="/servers/1/initialize"' not in text  # UI dropped this; start auto-inits.
    assert 'action="/servers/1/delete"' in text  # inside the delete modal
    assert 'href="/blueprints/1"' in text
    assert 'data-sse-url="/servers/1/logs/stream"' in text
    # Steam launch-and-connect link (run + appid 550 = L4D2)
    assert 'href="steam://run/550//+connect%20' in text


def test_server_actions_fragment_polls_while_running(auth_client_with_server) -> None:
    with session_scope() as session:
        job = Job(user_id=1, server_id=1, operation="start", state="queued")
        session.add(job)
        session.flush()
        job_id = job.id

    response = auth_client_with_server.get("/servers/1/actions")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert 'id="server-actions"' in text
    assert "<html" not in text  # fragment, not a full page
    assert 'hx-trigger="every 2s"' in text
    assert f'data-sse-url="/jobs/{job_id}/stream"' in text


def test_server_actions_fragment_settles_when_terminal(auth_client_with_server) -> None:
    with session_scope() as session:
        session.add(Job(user_id=1, server_id=1, operation="start", state="succeeded"))

    response = auth_client_with_server.get("/servers/1/actions")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert 'id="server-actions"' in text
    # No polling once the latest job is terminal.
    assert "hx-trigger" not in text
    # No live job-log streaming either.
    assert "data-sse-url=\"/jobs/" not in text


def test_server_detail_shows_last_job_summary(auth_client_with_server) -> None:
    with session_scope() as session:
        job = Job(user_id=1, server_id=1, operation="start", state="queued")
        session.add(job)
        session.flush()
        job_id = job.id

    response = auth_client_with_server.get("/servers/1")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    # Active job → no Start/Stop/Reset, only the last-job sentence.
    assert 'action="/servers/1/start"' not in text
    assert f'href="/jobs/{job_id}"' in text
    assert 'href="/servers/1/jobs"' in text  # "show all" link
    assert "starting" in text  # gerund form for in-flight start
    # Recent Jobs table is gone.
    assert "Recent Jobs" not in text


def test_server_jobs_page_lists_server_jobs(auth_client_with_server) -> None:
    with session_scope() as session:
        session.add(Job(user_id=1, server_id=1, operation="initialize", state="succeeded"))
        session.add(Job(user_id=1, server_id=1, operation="stop", state="queued"))

    response = auth_client_with_server.get("/servers/1/jobs")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Jobs for alpha" in text
    assert "initialize" in text
    assert "stop" in text
    assert 'href="/servers/1"' in text


def test_job_detail_shows_metadata_and_log_stream(auth_client_with_server) -> None:
    with session_scope() as session:
        job = Job(user_id=1, server_id=1, operation="start", state="running")
        session.add(job)
        session.flush()
        session.add(JobLog(job_id=job.id, seq=1, stream="stdout", line="starting"))
        job_id = job.id

    response = auth_client_with_server.get(f"/jobs/{job_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert f"Job #{job_id}" in text
    assert "start" in text
    assert "running" in text
    assert 'href="/servers/1"' in text
    assert f'data-sse-url="/jobs/{job_id}/stream"' in text


def test_owner_can_cancel_queued_job(auth_client_with_server) -> None:
    with session_scope() as session:
        job = Job(user_id=1, server_id=1, operation="stop", state="queued")
        session.add(job)
        session.flush()
        job_id = job.id

    with auth_client_with_server.session_transaction() as sess:
        sess["csrf_token"] = "test-token"

    response = auth_client_with_server.post(
        f"/jobs/{job_id}/cancel",
        data={"next": f"/jobs/{job_id}"},
        headers={"X-CSRF-Token": "test-token"},
    )

    assert response.status_code == 302
    assert response.headers["Location"].endswith(f"/jobs/{job_id}")
    with session_scope() as session:
        cancelled = session.query(Job).filter(Job.id == job_id).one()
        lines = session.query(JobLog).filter(JobLog.job_id == job_id).all()
        assert cancelled.state == "cancelled"
        assert cancelled.exit_code == 1
        assert cancelled.finished_at is not None
        assert [line.line for line in lines] == ["job cancelled before execution"]


def test_owner_can_request_running_job_cancel(auth_client_with_server) -> None:
    with session_scope() as session:
        job = Job(user_id=1, server_id=1, operation="start", state="running")
        session.add(job)
        session.flush()
        job_id = job.id

    with auth_client_with_server.session_transaction() as sess:
        sess["csrf_token"] = "test-token"

    response = auth_client_with_server.post(
        f"/jobs/{job_id}/cancel",
        data={"next": f"/jobs/{job_id}"},
        headers={"X-CSRF-Token": "test-token"},
    )

    assert response.status_code == 302
    with session_scope() as session:
        cancelling = session.query(Job).filter(Job.id == job_id).one()
        lines = session.query(JobLog).filter(JobLog.job_id == job_id).all()
        assert cancelling.state == "cancelling"
        assert cancelling.finished_at is None
        assert [line.line for line in lines] == ["job cancellation requested; attempting to terminate running process"]


def test_non_owner_cannot_view_or_cancel_job(auth_client_with_server) -> None:
    with session_scope() as session:
        other = User(username="other", password_digest=hash_password("secret"), admin=False)
        session.add(other)
        session.flush()
        job = Job(user_id=other.id, server_id=None, operation="install", state="queued")
        session.add(job)
        session.flush()
        job_id = job.id

    with auth_client_with_server.session_transaction() as sess:
        sess["csrf_token"] = "test-token"

    assert auth_client_with_server.get(f"/jobs/{job_id}").status_code == 403
    assert (
        auth_client_with_server.post(f"/jobs/{job_id}/cancel", headers={"X-CSRF-Token": "test-token"}).status_code
        == 403
    )


def test_servers_page_links_server_names(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/servers")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert '<a href="/servers/1">alpha</a>' in text
    assert "View" not in text
    assert ">details<" not in text


def test_servers_page_has_creation_form(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/servers")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert 'method="post" action="/servers"' in text
    assert 'name="name"' in text
    assert 'name="port"' in text
    assert 'name="blueprint_id"' in text
    assert '<option value="1">default</option>' in text
    assert "Create server" in text


def test_non_admin_does_not_see_admin_nav(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/dashboard")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert 'href="/admin"' not in text


def test_admin_can_use_admin_pages(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'admin-pages.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        admin = User(username="admin", password_digest=hash_password("secret"), admin=True)
        session.add(admin)
        session.flush()
        session.add(Job(user_id=admin.id, server_id=None, operation="install", state="queued"))
        admin_id = admin.id

    client = app.test_client()
    with client.session_transaction() as sess:
        sess["user_id"] = admin_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    admin_page = client.get("/admin")
    assert admin_page.status_code == 200
    admin_html = admin_page.get_data(as_text=True)
    assert 'action="/admin/install"' in admin_html
    assert "/admin/global-overlays/refresh" not in admin_html
    assert "Global map overlays" not in admin_html
    assert client.get("/admin/users").status_code == 200
    jobs_response = client.get("/admin/jobs")
    assert jobs_response.status_code == 200
    assert 'href="/jobs/1"' in jobs_response.get_data(as_text=True)
    assert 'action="/jobs/1/cancel"' in jobs_response.get_data(as_text=True)
    assert 'href="/admin"' in client.get("/dashboard").get_data(as_text=True)


def test_admin_can_view_other_users_job(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'admin-job-view.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        admin = User(username="admin", password_digest=hash_password("secret"), admin=True)
        user = User(username="alice", password_digest=hash_password("secret"), admin=False)
        session.add_all([admin, user])
        session.flush()
        job = Job(user_id=user.id, server_id=None, operation="install", state="queued")
        session.add(job)
        session.flush()
        admin_id = admin.id
        job_id = job.id

    client = app.test_client()
    with client.session_transaction() as sess:
        sess["user_id"] = admin_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    response = client.get(f"/jobs/{job_id}")

    assert response.status_code == 200
    assert "alice" in response.get_data(as_text=True)


def test_admin_can_enqueue_runtime_install_job(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'admin-install.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        admin = User(username="admin", password_digest=hash_password("secret"), admin=True)
        session.add(admin)
        session.flush()
        admin_id = admin.id

    client = app.test_client()
    with client.session_transaction() as sess:
        sess["user_id"] = admin_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()
        sess["csrf_token"] = "test-token"

    response = client.post("/admin/install", headers={"X-CSRF-Token": "test-token"})

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/admin/jobs")
    with session_scope() as session:
        job = session.query(Job).one()
        assert job.user_id == admin_id
        assert job.server_id is None
        assert job.operation == "install"
        assert job.state == "queued"


def test_non_admin_cannot_open_admin_pages(auth_client_with_server) -> None:
    assert auth_client_with_server.get("/admin").status_code == 403
    assert auth_client_with_server.get("/admin/users").status_code == 403
    assert auth_client_with_server.get("/admin/jobs").status_code == 403
    with auth_client_with_server.session_transaction() as sess:
        sess["csrf_token"] = "test-token"
    assert auth_client_with_server.post("/admin/install", headers={"X-CSRF-Token": "test-token"}).status_code == 403


def test_anonymous_protected_page_redirects_to_login_with_next(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'anonymous-pages.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()
    client = app.test_client()

    response = client.get("/servers")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/login?next=/servers")


def test_root_redirects_by_auth_state(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'root-redirect.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()
    client = app.test_client()

    anonymous_response = client.get("/")
    assert anonymous_response.status_code == 302
    assert anonymous_response.headers["Location"].endswith("/login")

    with session_scope() as session:
        user = User(username="alice", password_digest=hash_password("secret"), admin=False)
        session.add(user)
        session.flush()
        user_id = user.id

    with client.session_transaction() as sess:
        sess["user_id"] = user_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    logged_in_response = client.get("/")
    assert logged_in_response.status_code == 302
    assert logged_in_response.headers["Location"].endswith("/dashboard")


def test_blueprint_page_private_visibility(user_client_and_other_blueprint) -> None:
    client, blueprint_id = user_client_and_other_blueprint
    response = client.get(f"/blueprints/{blueprint_id}")
    assert response.status_code == 403


def test_blueprint_pages_fixture_has_ordered_overlay_data(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/blueprints/1")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "standard" in text


def test_blueprints_page_links_blueprint_names(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/blueprints")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert '<a href="/blueprints/1">default</a>' in text
    assert "View" not in text


def test_blueprint_detail_has_ordered_overlay_form(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/blueprints/1")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert ">Overlays<" in text
    assert 'name="arguments"' in text
    assert 'name="config"' in text
    assert 'name="overlay_ids"' in text
    assert "data-overlay-list" in text
    assert "data-overlay-add" in text


def test_admin_jobs_page_renders_system_job(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'admin-system-job.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        admin = User(username="admin", password_digest=hash_password("secret"), admin=True)
        session.add(admin)
        session.flush()
        admin_id = admin.id

    admin_client = app.test_client()
    with admin_client.session_transaction() as sess:
        sess["user_id"] = admin_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    with session_scope() as db:
        db.add(Job(user_id=None, server_id=None, operation="refresh_workshop_items", state="queued"))

    response = admin_client.get("/admin/jobs")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "refresh_workshop_items" in text
    assert "system" in text


def test_non_admin_cannot_view_system_job(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'non-admin-system-job.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        user = User(username="alice", password_digest=hash_password("secret"), admin=False)
        session.add(user)
        session.flush()
        user_id = user.id

    user_client = app.test_client()
    with user_client.session_transaction() as sess:
        sess["user_id"] = user_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    with session_scope() as db:
        job = Job(user_id=None, server_id=None, operation="refresh_workshop_items", state="queued")
        db.add(job)
        db.flush()
        job_id = job.id

    response = user_client.get(f"/jobs/{job_id}")
    assert response.status_code == 403


def test_overlay_create_modal_offers_script_type(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/overlays")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert 'value="workshop"' in text
    assert 'value="script"' in text


def _seed_overlay(name: str, type_: str, user_id: int) -> int:
    with session_scope() as s:
        overlay = Overlay(name=name, path="", type=type_, user_id=user_id)
        s.add(overlay)
        s.flush()
        overlay.path = str(overlay.id)
        s.flush()
        return overlay.id


def test_overlay_detail_script_section(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("build", "script", user_id)

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert '<textarea name="script"' in text
    # Two compound submits replaced standalone Rebuild/Wipe.
    assert "Save and build" in text
    assert "Save, reset and rebuild" in text
    assert "Rebuild" not in text  # no standalone Rebuild button
    assert "Last build" not in text  # state-badge replaces this label
    # Build-status badge is rendered (initial state for a fresh overlay).
    assert "never built" in text


def test_overlay_build_status_fragment_polls_while_running(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("polling", "script", user_id)
    with session_scope() as s:
        job = Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="running")
        s.add(job)
        s.flush()
        job_id = job.id

    response = auth_client_with_server.get(f"/overlays/{overlay_id}/build-status")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert 'id="overlay-build-status"' in text
    assert "<html" not in text  # fragment, not a full page
    assert 'hx-trigger="every 2s"' in text
    assert f'data-sse-url="/jobs/{job_id}/stream"' in text


def test_overlay_build_status_fragment_settles_when_terminal(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("settled", "script", user_id)
    with session_scope() as s:
        s.add(Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="succeeded"))

    response = auth_client_with_server.get(f"/overlays/{overlay_id}/build-status")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "hx-trigger" not in text
    assert "data-sse-url=\"/jobs/" not in text


def test_overlay_action_buttons_hidden_during_build(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("inflight", "script", user_id)
    with session_scope() as s:
        s.add(Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="running"))

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    # Submit buttons hidden while a build is in flight.
    assert "Save and build" not in text
    assert "Save, reset and rebuild" not in text
    # Status partial renders the building badge.
    assert "building…" in text


def test_overlay_detail_workshop_section_unchanged(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("ws", "workshop", user_id)

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Workshop items" in text


def test_overlay_detail_links_to_overlay_jobs_page(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("scripted", "script", user_id)
    # The "show all" link only appears once at least one build has happened
    # (otherwise the build-status partial has nothing to summarize).
    with session_scope() as s:
        s.add(Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="succeeded"))

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert f'href="/overlays/{overlay_id}/jobs"' in text
    assert "Save and build" in text


def test_overlay_jobs_page_lists_overlay_builds(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("scripted", "script", user_id)
    other_overlay_id = _seed_overlay("other", "script", user_id)

    with session_scope() as session:
        session.add(Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="succeeded"))
        session.add(Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="queued"))
        # Job for a different overlay must not appear.
        session.add(Job(user_id=user_id, overlay_id=other_overlay_id, operation="build_overlay", state="succeeded"))

    response = auth_client_with_server.get(f"/overlays/{overlay_id}/jobs")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Build jobs for scripted" in text
    assert text.count("build_overlay") == 2
    assert f'href="/overlays/{overlay_id}"' in text


def test_overlay_jobs_page_404_for_unknown_overlay(auth_client_with_server) -> None:
    response = auth_client_with_server.get("/overlays/9999/jobs")
    assert response.status_code == 404


def test_overlay_jobs_page_403_for_other_users_private_overlay(tmp_path, monkeypatch) -> None:
    db_url = f"sqlite:///{tmp_path/'overlay-jobs-403.db'}"
    monkeypatch.setenv("DATABASE_URL", db_url)
    app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"})
    init_db()

    with session_scope() as session:
        owner = User(username="owner", password_digest=hash_password("x"), admin=False)
        other = User(username="other", password_digest=hash_password("x"), admin=False)
        session.add_all([owner, other])
        session.flush()
        owner_id = owner.id
        other_id = other.id

    overlay_id = _seed_overlay("private", "script", owner_id)

    client = app.test_client()
    with client.session_transaction() as sess:
        sess["user_id"] = other_id
        sess["pw_changed_at"] = datetime.now(UTC).isoformat()

    response = client.get(f"/overlays/{overlay_id}/jobs")
    assert response.status_code == 403


def test_overlay_detail_no_global_source_block(auth_client_with_server) -> None:
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("ws", "workshop", user_id)

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert "Global source" not in text
    assert "source_url" not in text


def test_workshop_overlay_detail_renders_refresh_button(auth_client_with_server) -> None:
    """The owner sees a 'Refresh from Steam' button on their workshop overlay."""
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("ws-refresh-button", "workshop", user_id)

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Refresh from Steam" in text
    assert f'action="/overlays/{overlay_id}/refresh"' in text


def test_workshop_overlay_refresh_button_hidden_during_build(auth_client_with_server) -> None:
    """While a build is in flight the Refresh button hides, matching the Add form."""
    with session_scope() as s:
        user_id = s.query(User).filter_by(username="alice").one().id
    overlay_id = _seed_overlay("ws-refresh-hidden", "workshop", user_id)
    with session_scope() as s:
        s.add(Job(user_id=user_id, overlay_id=overlay_id, operation="build_overlay", state="running"))

    response = auth_client_with_server.get(f"/overlays/{overlay_id}")
    text = response.get_data(as_text=True)

    assert response.status_code == 200
    assert "Refresh from Steam" not in text
    # Positive companion: confirm the build-running guard actually fired,
    # otherwise the negative could pass vacuously on a broken page.
    assert "building…" in text
