from pathlib import Path

import pytest


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


def _login(client, level="master"):
    with client.session_transaction() as session:
        session.clear()
        session.update(user_id=7, access_level=level)


def test_master_sidebar_uses_one_link_per_group(client):
    _login(client)
    text = client.get("/crm/dashboard").get_data(as_text=True)

    assert text.count('data-panel="exports"') == 1
    assert text.count('data-panel="team"') == 1
    assert text.count('data-panel="insights"') == 1
    assert 'data-panel="statistics"' not in text and 'data-panel="leady"' not in text
    assert 'overflow-y-auto' in text
    assert '[&_.nav-link]:py-2' in text
    for old_sidebar_panel in ("export-packages", "export-jobs", "agents", "branches"):
        assert f'data-panel="{old_sidebar_panel}"' not in text

    assert 'id="panel-exports"' in text
    assert 'id="panel-team"' in text
    assert 'id="panel-insights"' in text
    assert 'data-dashboard-tab="export-packages"' in text
    assert 'data-dashboard-tab="export-jobs"' in text
    assert 'data-dashboard-tab="agents"' in text
    assert 'data-dashboard-tab="branches"' in text
    assert 'data-dashboard-tab="statistics"' not in text
    assert 'id="panel-statistics"' not in text
    assert 'id="panel-leady"' in text
    assert text.index('data-dashboard-tab="export-jobs"') < text.index('data-dashboard-tab="export-packages"')


@pytest.mark.parametrize(
    ("legacy_panel", "group_id", "tab_id"),
    [
        ("export-packages", "panel-exports", "export-packages"),
        ("export-jobs", "panel-exports", "export-jobs"),
        ("agents", "panel-team", "agents"),
        ("branches", "panel-team", "branches"),
        ("leady", "panel-insights", "leady"),
    ],
)
def test_legacy_panel_links_open_the_matching_group_tab(client, legacy_panel, group_id, tab_id):
    _login(client)
    text = client.get(f"/crm/dashboard?panel={legacy_panel}").get_data(as_text=True)

    assert f'id="{group_id}"' in text
    assert f'window.DASHBOARD_INITIAL_PANEL = "{legacy_panel}"' in text
    if tab_id == "leady":
        assert 'id="panel-leady"' in text
    else:
        assert f'data-dashboard-tab="{tab_id}"' in text


@pytest.mark.parametrize("panel", ["exports", "export-packages", "export-jobs"])
def test_export_group_and_legacy_links_remain_master_only(client, panel):
    _login(client, "agent")
    assert client.get(f"/crm/dashboard?panel={panel}").status_code == 403


def test_dashboard_script_maps_child_panels_to_groups_and_dispatches_child_event():
    source = (ROOT / "InvestmentManager/static/js/dashboard.js").read_text(encoding="utf-8")

    assert "exports: ['export-jobs', 'export-packages']" in source
    assert "team: ['agents', 'branches']" in source
    assert "insights: ['leady']" in source
    assert "window.showDashboardTab = showDashboardTab" in source
    assert "detail: { panelId }" in source
