from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]


def test_daily_sales_canvas_is_primary_and_fallback_is_opt_in():
    css = (ROOT / "web/static/css/page-daily-sales.css").read_text(encoding="utf-8")
    script = (ROOT / "web/static/js/page-daily-sales.js").read_text(encoding="utf-8")

    assert ".chart-container.has-html-chart canvas" not in css
    assert ".chart-container.chart-fallback-active canvas" in css
    assert ".chart-container.chart-empty-active canvas" in css
    assert ".chart-container:not(.chart-fallback-active) .chart-fallback-list" in css
    assert "node.content && node.content.textContent" in script
    assert "chart-empty-active" in script
    assert "Math.abs(Number(value)) > 1e-9" in script
    render_body = script.split("function renderAllCharts()", 1)[1].split("function bootCharts()", 1)[0]
    assert "renderHtmlChartFallbacks();" not in render_body
    assert "catch(error =>" in script
    assert "renderHtmlChartFallbacks();" in script.split("catch(error =>", 1)[1]


def test_growth_analysis_canvas_is_primary_and_fallback_is_opt_in():
    css = (ROOT / "web/static/css/page-growth-bem.css").read_text(encoding="utf-8")
    script = (ROOT / "web/static/js/page-growth.js").read_text(encoding="utf-8")

    assert ".ga-chart-card__body.has-html-chart canvas" not in css
    assert ".ga-chart-card__body.chart-fallback-active canvas" in css
    assert ".ga-chart-card__body.chart-empty-active canvas" in css
    assert ".ga-chart-card__body:not(.chart-fallback-active) .ga-chart-snapshot" in css
    assert "node.content && node.content.textContent" in script
    assert "chart-empty-active" in script
    assert "Math.abs(Number(value)) > 1e-9" in script
    render_body = script.split("function renderCharts()", 1)[1].split("function bootCharts()", 1)[0]
    assert "renderHtmlChartFallbacks();" not in render_body
    assert "catch(error =>" in script
    assert "renderHtmlChartFallbacks();" in script.split("catch(error =>", 1)[1]


def test_chart_theme_has_cdn_timeout_and_fallback_sources():
    script = (ROOT / "web/static/js" / "analysis-chart-theme.js").read_text(encoding="utf-8")

    assert "CHART_LOAD_TIMEOUT_MS" in script
    assert "Chart.js 載入逾時" in script
    assert "cdn.jsdelivr.net/npm/chart.js@4.4.6" in script
    assert "unpkg.com/chart.js@4.4.6" in script
    assert "cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.6" in script


def test_sales_chart_runtime_guard_rejects_axis_only_canvases():
    script = (ROOT / "scripts" / "check_sales_charts_runtime.js").read_text(encoding="utf-8")

    assert "nonZeroPoints" in script
    assert "colorPixels" in script
    assert "has no colored chart marks" in script
    assert "has no non-zero dataset values" in script
