import importlib.util
import pathlib


def load_module():
    path = pathlib.Path(__file__).resolve().parents[1] / "render" / "dashboards_render_atlas.py"
    spec = importlib.util.spec_from_file_location("scripts.dashboards_render_atlas", path)
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


def flatten_panels(panels):
    flat = []
    for panel in panels:
        flat.append(panel)
        flat.extend(panel.get("panels", []))
    return flat


def test_table_panel_options_and_filterable():
    mod = load_module()
    panel = mod.table_panel(
        1,
        "test",
        "metric",
        {"h": 1, "w": 1, "x": 0, "y": 0},
        unit="percent",
        transformations=[{"id": "labelsToFields", "options": {}}],
        instant=True,
        options={"showColumnFilters": False},
        filterable=False,
        footer={"show": False, "fields": "", "calcs": []},
        format="table",
    )
    assert panel["fieldConfig"]["defaults"]["unit"] == "percent"
    assert panel["fieldConfig"]["defaults"]["custom"]["filterable"] is False
    assert panel["options"]["showHeader"] is True
    assert panel["targets"][0]["format"] == "table"


def test_node_filter_and_expr_helpers():
    mod = load_module()
    expr = mod.node_filter("titan-.*")
    assert "label_replace" in expr
    cpu_expr = mod.node_cpu_expr("titan-.*")
    mem_expr = mod.node_mem_expr("titan-.*")
    assert "node_cpu_seconds_total" in cpu_expr
    assert "clamp_max(clamp_min(" in cpu_expr
    assert "* 100, 0), 100)" in cpu_expr
    assert "node_memory_MemAvailable_bytes" in mem_expr


def test_overview_availability_panel_uses_recorded_365d_rollup():
    mod = load_module()
    dashboard = mod.build_overview()
    panel = next(panel for panel in flatten_panels(dashboard["panels"]) if panel["id"] == 27)

    assert panel["title"] == "Atlas Availability (365d)"
    availability_expr = panel["targets"][0]["expr"]
    assert (
        'last_over_time(atlas:availability:ratio_365d{scope="atlas",definition="request-v4"}[48h])'
        in availability_expr
    )
    assert 'code=~"5.."' in availability_expr
    assert 'code=~"[1-5].."' in availability_expr
    assert "atlas:availability:failures_1d" not in availability_expr
    assert "atlas:availability:requests_1d" not in availability_expr
    assert "sum_over_time" not in availability_expr
    assert "kube_node_status_condition" not in availability_expr
    assert "kube_deployment_status_replicas_available" not in availability_expr
    assert panel["targets"][0]["instant"] is True
    assert "Every server-side 5xx" in panel["description"]
    assert "Replica counts, Grafana health" in panel["description"]
    assert "daily rollup job publishes one annual sample" in panel["description"]
    assert "keeps it for up to 48 hours" in panel["description"]


def test_overview_uses_readable_quality_power_and_gitops_panels():
    mod = load_module()
    dashboard = mod.build_overview()
    panels_by_title = {panel["title"]: panel for panel in flatten_panels(dashboard["panels"])}

    assert dashboard["links"] == [
        {"title": "Atlas Testing", "url": "/d/atlas-testing", "targetBlank": True}
    ]
    assert "atlas-jobs" not in repr(dashboard)
    assert "Platform Test Success Rate" not in panels_by_title
    assert panels_by_title["Test Category Health"]["type"] == "state-timeline"
    assert panels_by_title["Test Category Health"]["gridPos"] == {"h": 6, "w": 6, "x": 15, "y": 13}
    assert panels_by_title["Test Category Health"]["targets"][0]["legendFormat"] == "{{category}}"
    assert panels_by_title["Test Category Health"]["targets"][0]["format"] == "time_series"
    assert panels_by_title["Test Category Health"]["targets"][0]["range"] is True
    assert "${overview_suite:regex}" not in panels_by_title["Test Category Health"]["targets"][0]["expr"]
    assert mod.PLATFORM_TEST_SUITE_CANONICAL_MATCHER in panels_by_title["Test Category Health"]["targets"][0]["expr"]
    assert "platform_quality:test_category_health_rate:percent_1h" in panels_by_title["Test Category Health"]["targets"][0]["expr"]
    assert panels_by_title["Test Category Health"]["timeFrom"] == "24h"
    assert f'category=~"{mod.PLATFORM_TEST_OVERVIEW_CATEGORY_REGEX}"' in panels_by_title["Test Category Health"]["targets"][0]["expr"]
    assert "manual" not in mod.PLATFORM_TEST_OVERVIEW_CATEGORY_REGEX
    assert "unit" not in mod.PLATFORM_TEST_OVERVIEW_CATEGORY_REGEX
    assert panels_by_title["UPS History (Power Draw)"]["gridPos"] == {"h": 6, "w": 6, "x": 3, "y": 7}
    assert panels_by_title["Ariadne Run Volume"]["gridPos"] == {"h": 6, "w": 6, "x": 9, "y": 7}
    assert panels_by_title["Pyrphoros UPS Current"]["gridPos"]["w"] == 3
    assert panels_by_title["Current Enclosure Climate"]["gridPos"]["w"] == 3
    assert panels_by_title["UPS History (Power Draw)"]["options"]["legend"]["placement"] == "bottom"
    assert panels_by_title["UPS History (Power Draw)"]["options"]["legend"]["displayMode"] == "list"
    assert panels_by_title["UPS History (Power Draw)"]["fieldConfig"]["defaults"]["custom"]["drawStyle"] == "line"
    assert panels_by_title["UPS History (Power Draw)"]["fieldConfig"]["defaults"]["custom"]["fillOpacity"] == 22
    assert all(target["expr"].startswith("max(") for target in panels_by_title["UPS History (Power Draw)"]["targets"])
    ups_overrides = panels_by_title["UPS History (Power Draw)"]["fieldConfig"]["overrides"]
    ups_override_by_name = {override["matcher"]["options"]: override for override in ups_overrides}
    assert ups_override_by_name["Pyrphoros"]["properties"] == [
        {"id": "color", "value": {"mode": "fixed", "fixedColor": "dark-blue"}},
    ]
    assert ups_override_by_name["Statera"]["properties"] == [
        {"id": "color", "value": {"mode": "fixed", "fixedColor": "dark-yellow"}},
    ]
    assert panels_by_title["Ariadne Run Volume"]["fieldConfig"]["defaults"]["custom"]["drawStyle"] == "bars"
    assert panels_by_title["Ariadne Run Volume"]["options"]["legend"]["placement"] == "bottom"
    assert panels_by_title["Ariadne Run Volume"]["options"]["legend"]["displayMode"] == "list"
    assert "Fan History (0-10)" not in panels_by_title
    assert panels_by_title["Fan Intensity History"]["type"] == "state-timeline"
    assert panels_by_title["Fan Intensity History"]["gridPos"] == {"h": 6, "w": 6, "x": 9, "y": 13}
    assert panels_by_title["Fan Intensity History"]["fieldConfig"]["defaults"]["max"] == 10
    assert panels_by_title["Fan Intensity History"]["targets"][0]["legendFormat"] == "{{fan}}"
    fan_steps = panels_by_title["Fan Intensity History"]["fieldConfig"]["defaults"]["thresholds"]["steps"]
    assert [step["value"] for step in fan_steps] == [None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    assert fan_steps[0]["color"] == "#8f1d1d"
    assert fan_steps[5]["color"] == "#d4b106"
    assert fan_steps[-1]["color"] == "#1f60c4"
    fan_mappings = panels_by_title["Fan Intensity History"]["fieldConfig"]["defaults"]["mappings"][0]["options"]
    assert fan_mappings["0"]["text"] == "Off"
    assert fan_mappings["10"]["text"] == "10"
    assert "Tent Interior" in panels_by_title["Fan Intensity History"]["targets"][0]["expr"]
    assert panels_by_title["Fan Intensity History"]["options"]["legend"]["displayMode"] == "list"
    assert panels_by_title["Fan Intensity History"]["options"]["legend"]["showLegend"] is False
    assert panels_by_title["Fan Intensity History"]["options"]["mergeValues"] is False
    assert panels_by_title["Fan Intensity History"]["options"]["showValue"] == "auto"

    assert panels_by_title["Flux Source"]["type"] == "stat"
    assert panels_by_title["Flux Source"]["gridPos"] == {"h": 2, "w": 3, "x": 21, "y": 7}
    assert panels_by_title["Flux Source"]["targets"][0]["legendFormat"] == "{{branch}}"
    assert panels_by_title["Current Gate Health"]["gridPos"] == {"h": 2, "w": 3, "x": 21, "y": 9}
    assert "platform_quality:test_category_health_rate:percent_1h" in panels_by_title["Current Gate Health"]["targets"][0]["expr"]
    assert panels_by_title["CI Run Success (24h)"]["gridPos"] == {"h": 2, "w": 3, "x": 21, "y": 11}
    assert panels_by_title["Suites With Runs (24h)"]["gridPos"] == {"h": 2, "w": 3, "x": 21, "y": 15}
    suites_reporting_expr = panels_by_title["Suites With Runs (24h)"]["targets"][0]["expr"]
    assert "> bool 0" in suites_reporting_expr
    assert mod.PLATFORM_TEST_SUITE_CANONICAL_MATCHER in suites_reporting_expr
    assert "bstein-home" not in suites_reporting_expr
    assert "published quality-gate run" in panels_by_title["Suites With Runs (24h)"]["description"]
    assert panels_by_title["Avg Coverage"]["gridPos"] == {"h": 2, "w": 3, "x": 21, "y": 17}
    assert "LOC Clean Suites" not in panels_by_title
    assert panels_by_title["GitOps Health"]["type"] == "state-timeline"
    assert panels_by_title["GitOps Health"]["gridPos"] == {"h": 6, "w": 6, "x": 15, "y": 7}
    gitops_expr = panels_by_title["GitOps Health"]["targets"][0]["expr"]
    assert "Kustomizations Not Suspended" in gitops_expr
    assert "HelmReleases Not Suspended" in gitops_expr
    assert panels_by_title["Test Category Health"]["type"] == "state-timeline"
    assert panels_by_title["Test Category Health"]["options"]["legend"]["showLegend"] is False
    assert panels_by_title["Test Category Health"]["options"]["mergeValues"] is False
    assert panels_by_title["Test Category Health"]["options"]["showValue"] == "auto"
    assert panels_by_title["Test Category Health"]["options"]["rowHeight"] == 0.9
    assert panels_by_title["Test Category Health"]["targets"][0]["legendFormat"] == "{{category}}"
    assert 'label_set(vector(0), "category", "none")' in panels_by_title["Test Category Health"]["targets"][0]["expr"]
    assert not any(variable["name"] == "overview_suite" for variable in dashboard["templating"]["list"])

    pvc_backup_expr = panels_by_title["PVC Backup Health / Age"]["targets"][0]["expr"]
    assert "backup-telemetry-missing" in pvc_backup_expr
    assert 'pvc_backup_(count|last_success_timestamp_seconds|health_reason)' in pvc_backup_expr

    gpu_expr = panels_by_title["Namespace GPU Utilization"]["targets"][0]["expr"]
    assert "nvidia_namespace_gpu_sm_util_percent" in gpu_expr
    assert "nvidia_gpu_device_utilization_percent" in gpu_expr
    assert "jetson_gr3d_active_seconds_total" in gpu_expr
    assert "increase" in gpu_expr
    assert "sum_over_time" not in gpu_expr
    assert "count_over_time" not in gpu_expr
    assert "avg_over_time" in gpu_expr
    assert "$__range" in gpu_expr
    assert "$__range_s" in gpu_expr
    assert "sum by (namespace)" in gpu_expr
    assert 'namespace", "shared"' not in gpu_expr
    assert "kube_pod_container_resource_requests" in gpu_expr
    assert mod.GPU_RESOURCE_REGEX in gpu_expr
    assert '"gpu_source", "nvidia"' in gpu_expr
    assert '"gpu_source", "jetson"' in gpu_expr
    assert "100 *" in gpu_expr
    assert "100 -" not in gpu_expr
    assert 'namespace", "unattributed"' in gpu_expr
    assert 'namespace", "idle"' in gpu_expr
    assert panels_by_title["Namespace GPU Utilization"]["targets"][0]["instant"] is True
    assert "selected time range" in panels_by_title["Namespace GPU Utilization"]["description"]
    assert "continuously sampled" in panels_by_title["Namespace GPU Utilization"]["description"]
    assert "Kubernetes shared-GPU allocations" in panels_by_title["Namespace GPU Utilization"]["description"]


def test_gpu_node_panel_prefers_stable_process_metrics_and_covers_all_gpu_families():
    mod = load_module()
    dashboard = mod.build_gpu_dashboard()
    panels_by_title = {panel["title"]: panel for panel in flatten_panels(dashboard["panels"])}

    node_expr = panels_by_title["GPU Util by Node"]["targets"][0]["expr"]
    assert "nvidia_gpu_device_utilization_percent" in node_expr
    assert "DCGM_FI_DEV_GPU_UTIL" in node_expr
    assert "jetson_gr3d_freq_percent" in node_expr
    assert "unless on(node)" in node_expr
    assert mod.GPU_NODES == ["titan-20", "titan-21", "titan-22", "titan-24"]

    process_expr = panels_by_title["GPU Processes by Pod"]["targets"][0]["expr"]
    assert "nvidia_process_gpu_sm_util_percent" in process_expr
    assert "DCGM_FI_DEV_GPU_UTIL" not in process_expr


def test_overview_and_testing_panels_all_have_concise_descriptions():
    mod = load_module()

    for dashboard in [mod.build_overview(), mod.build_jobs_dashboard(), mod.build_testing_dashboard()]:
        panels = flatten_panels(dashboard["panels"])
        assert all(panel.get("description") for panel in panels if panel["type"] != "row")
        assert "85.7" not in repr(dashboard)


def test_render_configmap_writes(tmp_path):
    mod = load_module()
    mod.DASHBOARD_DIR = tmp_path / "dash"
    mod.ROOT = tmp_path
    uid = "atlas-test"
    info = {"configmap": tmp_path / "cm.yaml"}
    data = {"title": "Atlas Test"}
    mod.write_json(uid, data)
    mod.render_configmap(uid, info)
    json_path = mod.DASHBOARD_DIR / f"{uid}.json"
    assert json_path.exists()
    content = (tmp_path / "cm.yaml").read_text()
    assert "kind: ConfigMap" in content
    assert f"{uid}.json" in content


def test_testing_suite_variable_uses_configured_suite_values_only():
    mod = load_module()
    variable = mod.testing_suite_variable()
    configured_matcher = "|".join(mod.PLATFORM_TEST_SUITE_NAMES)
    legacy_names = {"bstein-home", "data-prepper", "titan-iac", "pegasus-health"}
    out_of_scope_names = {"arcanagon", "typhon"}

    assert variable["allValue"] == configured_matcher
    assert not any(alias in variable["query"] for alias in legacy_names)
    assert not any(alias in variable["allValue"] for alias in legacy_names)
    assert not any(name in variable["query"] for name in out_of_scope_names)
    assert not any(name in variable["allValue"] for name in out_of_scope_names)
    assert [option["value"] for option in variable["options"]] == mod.PLATFORM_TEST_SUITE_NAMES
    assert "lesavka" in variable["allValue"]
    assert any(option["value"] == "lesavka" for option in variable["options"])
    assert not any(
        option["value"] in out_of_scope_names for option in variable["options"]
    )


def test_testing_dashboard_is_public_but_jobs_dashboard_remains_internal():
    mod = load_module()
    jobs = mod.build_jobs_dashboard()
    testing = mod.build_testing_dashboard()

    assert jobs["folderUid"] == mod.PRIVATE_FOLDER
    assert jobs["editable"] is True
    assert testing["uid"] == "atlas-testing"
    assert testing["folderUid"] == mod.PUBLIC_DASHBOARD_FOLDER
    assert testing["editable"] is False


def test_jobs_dashboard_separates_current_gate_health_from_reliability():
    mod = load_module()
    dashboard = mod.build_jobs_dashboard()
    panels_by_title = {panel["title"]: panel for panel in flatten_panels(dashboard["panels"])}
    variables_by_name = {item["name"]: item for item in dashboard["templating"]["list"]}

    test_variable = variables_by_name["test"]
    assert test_variable["query"].startswith("query_result(")
    assert "platform_quality:test_case_health_rate:percent_1h" in test_variable["query"]
    assert "platform_quality_gate_test_case_result" not in test_variable["query"]
    assert test_variable["regex"] == '/test="([^"]+)"/'
    branch_variable = variables_by_name["branch"]
    assert branch_variable["type"] == "custom"
    assert branch_variable["allValue"] == ".*"
    assert "platform_quality_gate_build_info" not in branch_variable["query"]
    assert "origin/main : origin/main" in branch_variable["query"]

    assert "Current Gate Health (%)" in panels_by_title
    assert "Suite Freshness (24h)" in panels_by_title
    assert "Latest Gate Health by Suite" in panels_by_title
    assert "Latest Gate Checks Passing by Suite" not in panels_by_title
    assert "CI Run Success by Suite (24h)" in panels_by_title
    assert "CI Run Success by Suite (7d rolling)" in panels_by_title
    assert "Daily Run Volume (Selected Scope)" in panels_by_title
    assert "Coverage History by Suite" in panels_by_title
    assert "Files <=500 LOC History by Suite" in panels_by_title
    assert "Run Reliability History by Suite" not in panels_by_title
    assert "Current Gate Health by Suite" not in panels_by_title
    assert "Coverage & LOC Compliance History" not in panels_by_title
    assert "Run Status Mix (30d)" not in panels_by_title
    assert "Failures by Suite (24h)" not in panels_by_title
    assert "Success Rate by Suite (24h)" not in panels_by_title

    current_gate_expr = panels_by_title["Latest Gate Health by Suite"]["targets"][0]["expr"]
    assert 'check)' in current_gate_expr
    assert "platform_quality:check_status:present_1h" in current_gate_expr
    assert "platform_quality:test_category_health_rate:percent_1h" in current_gate_expr
    assert "- 1" in current_gate_expr
    assert '.*_quality_gate_checks_total' not in current_gate_expr
    assert "last_over_time" not in current_gate_expr
    assert 'label_replace' not in current_gate_expr
    assert f'check=~"{mod.PLATFORM_TEST_ALWAYS_REQUIRED_CHECK_REGEX}"' in current_gate_expr
    assert f'suite=~"{mod.PLATFORM_TEST_SUPPLY_CHAIN_REQUIRED_MATCHER}"' in current_gate_expr
    assert 'check="supply_chain"' in current_gate_expr
    assert f'check=~"{mod.PLATFORM_TEST_STANDARD_CHECK_REGEX}"' not in current_gate_expr
    assert 'status=~"ok|passed|success|not_applicable|skipped|na|n/a"' in current_gate_expr
    assert 'status!~"ok|passed|success|not_applicable|skipped|na|n/a"' in current_gate_expr
    assert "unless on(suite, check)" in current_gate_expr
    assert "tlast_over_time" not in current_gate_expr
    assert panels_by_title["Current Gate Health (%)"]["gridPos"] == {"h": 4, "w": 3, "x": 0, "y": 0}
    current_gate_stat_expr = panels_by_title["Current Gate Health (%)"]["targets"][0]["expr"]
    assert "platform_quality:test_category_health_rate:percent_1h" in current_gate_stat_expr
    assert "- 1" not in current_gate_stat_expr
    assert panels_by_title["Suite Freshness (24h)"]["gridPos"] == {"h": 4, "w": 3, "x": 15, "y": 0}
    suite_freshness_expr = panels_by_title["Suite Freshness (24h)"]["targets"][0]["expr"]
    assert "platform_quality:suite_runs:increase_24h" in suite_freshness_expr
    assert "max_over_time(platform_quality_gate_runs_total" not in suite_freshness_expr
    assert "[7d:1h]" in panels_by_title["CI Run Success Rate (7d)"]["targets"][0]["expr"]
    assert panels_by_title["Latest Gate Health by Suite"]["gridPos"]["w"] == 6
    assert panels_by_title["CI Run Success by Suite (24h)"]["gridPos"]["w"] == 6
    assert panels_by_title["Coverage by Suite (Latest, gate 95)"]["gridPos"] == {"h": 7, "w": 6, "x": 12, "y": 4}
    assert panels_by_title["Files <=500 LOC by Suite (Latest)"]["gridPos"] == {"h": 7, "w": 6, "x": 18, "y": 4}

    reliability_panel = panels_by_title["CI Run Success by Suite (24h)"]
    reliability_expr = reliability_panel["targets"][0]["expr"]
    assert "platform_quality:suite_runs:increase_24h" in reliability_expr
    assert "platform_quality_gate_runs_total" not in reliability_expr
    assert "> 0" in reliability_expr
    assert "- 1" in reliability_expr
    assert reliability_expr.startswith("sort(")
    assert reliability_panel["fieldConfig"]["defaults"]["mappings"] == [
        {"type": "value", "options": {"-1": {"text": "no runs"}}}
    ]

    rolling_panel = panels_by_title["CI Run Success by Suite (7d rolling)"]
    assert rolling_panel["type"] == "state-timeline"
    assert "[7d:1h]" in rolling_panel["targets"][0]["expr"]
    category_panel = panels_by_title["Test Category Health History"]
    assert category_panel["type"] == "state-timeline"
    assert "category" in category_panel["targets"][0]["expr"]
    assert category_panel["targets"][0]["format"] == "time_series"
    assert category_panel["targets"][0]["range"] is True
    assert "platform_quality:test_category_health_rate:percent_1h" in category_panel["targets"][0]["expr"]
    assert 'test!=""' not in category_panel["targets"][0]["expr"]
    assert f'category=~"{mod.PLATFORM_TEST_CATEGORY_REGEX}"' in category_panel["targets"][0]["expr"]
    assert "installer" not in mod.PLATFORM_TEST_CATEGORY_REGEX
    assert "Use the Suite filter" in category_panel["description"]
    assert "skipped tests are healthy" in category_panel["description"]

    tests_failure_expr = panels_by_title["Tests Failure Rate"]["targets"][0]["expr"]
    assert "platform_quality:check_failed_flag:present_1h" in tests_failure_expr
    assert "platform_quality:check_seen_flag:present_1h" in tests_failure_expr
    assert "platform_quality:check_status:present_1h" not in tests_failure_expr

    tests_healthy_expr = panels_by_title["Tests Healthy Rate"]["targets"][0]["expr"]
    assert "platform_quality:check_healthy_flag:present_1h" in tests_healthy_expr
    assert "platform_quality:check_seen_flag:present_1h" in tests_healthy_expr

    problematic_expr = panels_by_title["Problematic Tests Over Time (Top failures)"]["targets"][0]["expr"]
    assert "platform_quality:test_case_status:count_1h" in problematic_expr
    assert "platform_quality_gate_test_case_result" not in problematic_expr
    assert "[24h:1h]" in problematic_expr
    assert ">= 2" in problematic_expr
    assert "@ end()" in problematic_expr

    coverage_panel = panels_by_title["Coverage History by Suite"]
    loc_panel = panels_by_title["Files <=500 LOC History by Suite"]
    assert coverage_panel["type"] == "state-timeline"
    assert loc_panel["type"] == "state-timeline"
    assert coverage_panel["targets"][0]["expr"] != loc_panel["targets"][0]["expr"]
    assert "platform_quality:suite_coverage_percent:latest_1h" in coverage_panel["targets"][0]["expr"]
    assert "platform_quality:suite_source_files_total:latest_1h" in loc_panel["targets"][0]["expr"]
    assert "platform_quality:suite_source_lines_over_500_total:latest_1h" in loc_panel["targets"][0]["expr"]
    assert "tlast_over_time" not in coverage_panel["targets"][0]["expr"]
    assert "tlast_over_time" not in loc_panel["targets"][0]["expr"]
    assert "platform_quality_gate_workspace_line_coverage_percent" not in panels_by_title["Coverage by Suite (Latest, gate 95)"]["targets"][0]["expr"]
    assert "platform_quality:suite_coverage_percent:latest_1h" in panels_by_title["Avg Coverage (%)"]["targets"][0]["expr"]
    assert panels_by_title["Daily Run Volume (Selected Scope)"]["gridPos"] == {"h": 8, "w": 8, "x": 0, "y": 27}
    assert coverage_panel["gridPos"] == {"h": 8, "w": 8, "x": 8, "y": 27}
    assert loc_panel["gridPos"] == {"h": 8, "w": 8, "x": 16, "y": 27}

    run_volume_panel = panels_by_title["Daily Run Volume (Selected Scope)"]
    assert run_volume_panel["fieldConfig"]["defaults"]["custom"]["drawStyle"] == "bars"
    assert "[$__interval]" not in run_volume_panel["targets"][0]["expr"]


def test_jobs_dashboard_bar_gauges_use_solid_threshold_colors():
    mod = load_module()
    dashboard = mod.build_jobs_dashboard()
    panels = flatten_panels(dashboard["panels"])
    bar_gauges = [panel for panel in panels if panel["type"] == "bargauge"]

    assert bar_gauges
    assert all(panel["options"]["displayMode"] == "basic" for panel in bar_gauges)
    assert all(
        panel["fieldConfig"]["defaults"]["color"]["mode"] == "thresholds"
        for panel in bar_gauges
    )

    reliability_panel = next(
        panel for panel in panels if panel["title"] == "CI Run Success by Suite (24h)"
    )
    threshold_steps = reliability_panel["fieldConfig"]["defaults"]["thresholds"]["steps"]

    assert {"color": "dark-yellow", "value": 93} in threshold_steps
    assert {"color": "dark-blue", "value": 100} in threshold_steps


def test_jobs_dashboard_collapses_heavy_drilldowns_for_light_first_paint():
    mod = load_module()
    dashboard = mod.build_jobs_dashboard()
    panels = dashboard["panels"]
    rows = [panel for panel in panels if panel["type"] == "row"]
    visible_query_panels = [panel for panel in panels if panel["type"] != "row"]
    nested_panels_by_title = {
        child["title"]: child
        for row in rows
        for child in row.get("panels", [])
    }

    assert len(panels) == 18
    assert len(visible_query_panels) == 12
    assert sum(len(panel.get("targets", [])) for panel in visible_query_panels) == 12
    assert all(
        panel["title"] != "Coverage Gap to 95% by Suite"
        for panel in visible_query_panels
    )
    assert [row["title"] for row in rows] == [
        "CI Runs And Test Result History",
        "Check Failure Rates By Suite",
        "Check Healthy Rates By Suite",
        "Test Drilldowns And Problem Tests",
        "Telemetry Completeness And Branches",
        "SonarQube Project Health",
    ]
    assert all(row["collapsed"] for row in rows)

    assert "Coverage Failure Rate" in nested_panels_by_title
    assert "Supply Chain Healthy Rate" in nested_panels_by_title
    assert "Test Category Health History" in nested_panels_by_title
    assert "Selected Test Pass Rate History" in nested_panels_by_title
    assert "Coverage Metrics Present by Suite" in nested_panels_by_title
    assert "SonarQube API Up" in nested_panels_by_title

    failure_rate_panel = nested_panels_by_title["Coverage Failure Rate"]
    assert failure_rate_panel["type"] == "state-timeline"
    assert failure_rate_panel["fieldConfig"]["defaults"]["unit"] == "percent"
    assert failure_rate_panel["fieldConfig"]["defaults"]["max"] == 100
    assert failure_rate_panel["fieldConfig"]["defaults"]["thresholds"]["steps"][0]["color"] == "dark-blue"
    assert "increase(" not in failure_rate_panel["targets"][0]["expr"]
    assert "platform_quality:check_failed_flag:present_1h" in failure_rate_panel["targets"][0]["expr"]
    assert "platform_quality:check_seen_flag:present_1h" in failure_rate_panel["targets"][0]["expr"]
    assert "platform_quality:check_status:present_1h" not in failure_rate_panel["targets"][0]["expr"]
    assert '.*_quality_gate_checks_total' not in failure_rate_panel["targets"][0]["expr"]
    assert "last_over_time" not in failure_rate_panel["targets"][0]["expr"]
    assert 'label_replace' not in failure_rate_panel["targets"][0]["expr"]
    assert "0 *" in failure_rate_panel["targets"][0]["expr"]
    assert "and on(suite)" not in failure_rate_panel["targets"][0]["expr"]

    pass_rate_panel = nested_panels_by_title["Selected Test Pass Rate History"]
    assert pass_rate_panel["type"] == "state-timeline"
    assert "platform_quality:test_case_pass_rate:percent_1h" in pass_rate_panel["targets"][0]["expr"]
    assert "platform_quality_gate_test_case_result" not in pass_rate_panel["targets"][0]["expr"]

    pass_fail_panel = nested_panels_by_title["Selected Test Pass/Fail History"]
    assert pass_fail_panel["fieldConfig"]["defaults"]["custom"]["drawStyle"] == "bars"
    assert all(
        "platform_quality:test_case_status:count_1h" in target["expr"]
        for target in pass_fail_panel["targets"]
    )

    problematic_panel = nested_panels_by_title["Problematic Tests Over Time (Top failures)"]
    assert problematic_panel["type"] == "state-timeline"
    assert problematic_panel["gridPos"]["w"] == 24
    assert 'test!=""' in problematic_panel["targets"][0]["expr"]
    assert "vector(0)" not in problematic_panel["targets"][0]["expr"]
    assert problematic_panel["fieldConfig"]["defaults"]["thresholds"]["steps"] == [
        {"color": "dark-blue", "value": None},
        {"color": "dark-green", "value": 2},
        {"color": "dark-yellow", "value": 3},
        {"color": "dark-orange", "value": 5},
        {"color": "dark-red", "value": 8},
    ]
    assert "rolling 24h failure count" in problematic_panel["description"]
    assert "at least two recent failures" in problematic_panel["description"]

    sonar_mix_panel = nested_panels_by_title["Sonar Gate Status Mix (Selected)"]
    sonar_health_panel = nested_panels_by_title["Sonar Gate Health by Project"]
    assert sonar_mix_panel["gridPos"]["w"] == 4
    assert sonar_health_panel["gridPos"]["w"] == 8
    assert sonar_health_panel["type"] == "state-timeline"
    assert "platform_quality:sonar_gate_health_percent:latest_1h" in sonar_health_panel["targets"][0]["expr"]
    assert "sonarqube_project_quality_gate_pass" not in sonar_health_panel["targets"][0]["expr"]

    branch_panel = nested_panels_by_title["Primary Branch Clean by Suite (7d)"]
    recent_branch_panel = nested_panels_by_title["Recent Branch Evidence by Suite (7d)"]
    assert branch_panel["gridPos"]["x"] == 12
    assert recent_branch_panel["gridPos"]["x"] == 18
    assert "[7d:1h]" in recent_branch_panel["targets"][0]["expr"]
    assert "[7d:1h]" in branch_panel["targets"][0]["expr"]
    assert branch_panel["fieldConfig"]["defaults"]["unit"] == "percent"
    assert "unless on(suite)" in branch_panel["targets"][0]["expr"]
    assert "> bool 0" in branch_panel["targets"][0]["expr"]
    assert branch_panel["targets"][0]["expr"].startswith("sort(")
