import sys
import subprocess as sp
import importlib.resources as r


def _site_examples_logs():
    # Use packaged examples (what customers actually get)
    p = r.files("team_digest") / "examples" / "logs"
    return str(p)


def _run(cmd: str):
    print("$", cmd)
    r = sp.run(cmd, shell=True, text=True, capture_output=True)
    print(r.stdout)
    if r.returncode != 0:
        print(r.stderr, file=sys.stderr)
    return r


def test_weekly_counts_ok(tmp_path):
    out = tmp_path / "weekly.md"
    logs = _site_examples_logs()
    r = _run(
        f'team-digest weekly --logs-dir "{logs}" '
        f"--start 2025-10-13 --end 2025-10-19 "
        f'--output "{out}" --group-actions --emit-kpis --owner-breakdown'
    )
    assert r.returncode == 0
    t = out.read_text(encoding="utf-8")
    # Range line and KPIs
    assert "_Range: 2025-10-13 → 2025-10-19" in t
    assert "## Executive KPIs" in t
    # Actions present (sample examples yield 15)
    assert "Actions: 15" in t or "Actions:" in t


def test_daily_sections_ok(tmp_path):
    out = tmp_path / "daily.md"
    logs = _site_examples_logs()
    r = _run(
        f'team-digest daily --logs-dir "{logs}" '
        f'--date 2025-10-17 --output "{out}" --group-actions'
    )
    assert r.returncode == 0
    t = out.read_text(encoding="utf-8")
    for h in (
        "## Summary",
        "## Decisions",
        "## Actions",
        "## Risks",
        "## Dependencies",
        "## Notes",
    ):
        assert h in t


def test_monthly_footer_and_format(tmp_path):
    out = tmp_path / "monthly.md"
    logs = _site_examples_logs()
    r = _run(
        f'team-digest monthly --logs-dir "{logs}" '
        f'--output "{out}" --group-actions --emit-kpis --owner-breakdown'
    )
    assert r.returncode == 0
    t = out.read_text(encoding="utf-8")
    # Footer exists
    assert "Digest generated by team-digest v" in t
    # No raw backslash bullets
    assert "\\- " not in t
