#!/usr/bin/env python
from __future__ import annotations

import argparse
import datetime as dt
from pathlib import Path
from typing import Optional, Tuple, List

from .team_digest_runtime import aggregate_range

try:
    from . import __version__ as VERSION
except Exception:
    VERSION = "unknown"


def _write_output(text: str, output: Optional[str]) -> None:
    if output:
        p = Path(output)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(text, encoding="utf-8")
    else:
        print(text)


def _parse_date(s: str) -> dt.date:
    return dt.date.fromisoformat(s)


def _infer_range_from_logs(logs_dir: Path) -> Tuple[dt.date, dt.date]:
    """Fallback if dates aren’t provided: infer [min,max] from notes-YYYY-MM-DD.md in logs_dir."""
    dates: List[dt.date] = []
    for p in logs_dir.glob("notes-*.md"):
        try:
            d = dt.date.fromisoformat(p.stem.split("notes-")[1])
            dates.append(d)
        except Exception:
            pass
    if dates:
        return (min(dates), max(dates))
    today = dt.date.today()
    return (today, today)


def main() -> int:
    ap = argparse.ArgumentParser(
        prog="team-digest", description="Generate team digests from Markdown logs."
    )
    sub = ap.add_subparsers(dest="cmd", required=True)

    def add_common(p: argparse.ArgumentParser) -> None:
        p.add_argument(
            "--logs-dir", required=True, help="Directory containing Markdown daily logs"
        )
        p.add_argument("--output", help="Write digest to this file (stdout if omitted)")
        p.add_argument("--group-actions", action="store_true")
        p.add_argument("--flat-by-name", action="store_true")
        p.add_argument("--emit-kpis", action="store_true")
        p.add_argument("--owner-breakdown", action="store_true")
        p.add_argument("--owner-top", type=int, default=8)

    # daily
    p_daily = sub.add_parser(
        "daily", help="Generate a digest for a single day (YYYY-MM-DD)"
    )
    add_common(p_daily)
    p_daily.add_argument("--date", type=_parse_date, required=True)

    # weekly
    p_weekly = sub.add_parser("weekly", help="Generate a digest for a date range")
    add_common(p_weekly)
    p_weekly.add_argument("--start", type=_parse_date)
    p_weekly.add_argument("--end", type=_parse_date)

    # monthly
    p_monthly = sub.add_parser("monthly", help="Generate a monthly digest")
    add_common(p_monthly)
    p_monthly.add_argument("--start", type=_parse_date)
    p_monthly.add_argument("--end", type=_parse_date)

    args = ap.parse_args()
    logs_dir = Path(args.logs_dir)

    title: Optional[str] = None

    if args.cmd == "daily":
        start = end = args.date

    elif args.cmd == "weekly":
        start = getattr(args, "start", None)
        end = getattr(args, "end", None)
        if start is None or end is None:
            # default: last 7 days ending today
            end = end or dt.date.today()
            start = start or (end - dt.timedelta(days=6))

    else:  # monthly
        start = getattr(args, "start", None)
        end = getattr(args, "end", None)
        if start is None or end is None:
            # default: current month to today
            today = dt.date.today()
            month_start = today.replace(day=1)
            month_end = today
            start = start or month_start
            end = end or month_end
        # Explicit monthly title expected by tests: YYYY-MM
        title = f"Team Digest ({start:%Y-%m})"

    text = aggregate_range(
        logs_dir=logs_dir,
        start=start,
        end=end,
        title=title,  # only set for monthly; None keeps default header elsewhere
        group_actions=args.group_actions,
        flat_by_name=args.flat_by_name,
        emit_kpis=args.emit_kpis,
        owner_breakdown=args.owner_breakdown,
        owner_top=args.owner_top,
    )

    # Footer (matches your prior outputs)
    footer = (
        "\n---\n"
        f"_Digest generated by team-digest v{VERSION} — https://pypi.org/project/team-digest/_\n"
    )
    if not text.endswith("\n"):
        text += "\n"
    text += footer

    _write_output(text, getattr(args, "output", None))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
