from pdf_to_md_local.server import active_job_snapshot, begin_active_job, cancel_active_job, finish_active_job, json_response, static_file_for_path


def test_json_response_sets_cors_and_json_content_type():
    status, headers, body = json_response({"ok": True})

    assert status == 200
    assert headers["Content-Type"] == "application/json; charset=utf-8"
    assert headers["Access-Control-Allow-Origin"] == "*"
    assert headers["Access-Control-Allow-Private-Network"] == "true"
    assert b'"ok": true' in body


def test_json_response_echoes_origin_for_private_network_access():
    _, headers, _ = json_response({"ok": True}, origin="https://orc.thanganhai.com")

    assert headers["Access-Control-Allow-Origin"] == "https://orc.thanganhai.com"
    assert headers["Vary"] == "Origin"


def test_cancel_active_job_reports_no_active_job_when_idle():
    assert cancel_active_job() == {"ok": False, "error": "no_active_job"}
    assert active_job_snapshot() == {"active": False}


def test_cancel_active_job_sets_cancel_event():
    job = begin_active_job("Example.pdf")
    assert job is not None
    try:
        payload = cancel_active_job()
        assert payload["ok"] is True
        assert job["cancel_event"].is_set()
    finally:
        finish_active_job(job["job_id"])


def test_static_file_for_path_serves_local_app_shell():
    index = static_file_for_path("/")
    app_js = static_file_for_path("/app.js")

    assert index is not None
    assert index.name == "index.html"
    assert app_js is not None
    assert app_js.name == "app.js"
