import importlib.util
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
DASHBOARD = ROOT / "scripts/health/health_dashboard_v3.py"
YAZIO = ROOT / "scripts/health/yazio_nutrition_sync.py"


def test_dashboard_does_not_use_legacy_missing_as_zero_correlations():
    source = DASHBOARD.read_text(encoding="utf-8")

    assert "SELECT metric,lag_days,n,correlation" not in source
    assert "nutrition_correlations" not in source
    assert "symptom_by_day.get(d, 0)" not in source
    assert "symptom_map[d].get(dim,0)" not in source
    assert "<h3>Safe-/Trigger-Kandidaten</h3>" not in source
    assert "nutrition_treatment_phase_summary" not in source
    assert "nutrition_action_recommendations" not in source
    assert "for r in symptoms:\n        txt = str(r[\"schwergrad\"]" not in source
    assert "int(row[\"histamine_unknown_count\"] or 0) == 0" in source
    assert "calendar_axis(nutrition_rows_by_day)" in source
    assert "calendar_axis(quick_by_day, max_days=30)" in source
    assert "multimodal_correlation_results" in source
    assert "Fehlende Symptomtage werden nicht als symptomfrei interpretiert" in source
    assert "keine Ursache, Diagnose, Therapieempfehlung oder Entwarnung" in source


def test_dashboard_calendar_axis_preserves_fully_missing_days_as_gap_slots():
    spec = importlib.util.spec_from_file_location("health_dashboard_calendar_test", DASHBOARD)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    assert module.calendar_axis(["2026-01-01", "2026-01-03"]) == [
        "2026-01-01", "2026-01-02", "2026-01-03"
    ]
    assert module.calendar_axis(["2026-01-01", "2026-02-01"], max_days=3) == [
        "2026-01-30", "2026-01-31", "2026-02-01"
    ]
    axis = module.calendar_axis(["2026-01-01", "2026-01-03"])
    assert module.sparse_calendar_series(
        axis, {"2026-01-01": 1, "2026-01-03": 3}
    ) == [1, None, 3]


def test_yazio_refreshes_new_engine_after_changed_source_data():
    source = YAZIO.read_text(encoding="utf-8")

    assert "CORRELATIONS = BASE / \"scripts\" / \"multimodal_correlations.py\"" in source
    assert "nutrition_insights.py" not in source
    changed_block = source.index("if changed:\n        correlations = subprocess.run")
    dashboard_block = source.index("if changed and args.dashboard:")
    assert changed_block < dashboard_block
