#!/usr/bin/env python3
"""
list_handoffs.py — List handoff docs for a course.

CLI: python3 scripts/list_handoffs.py --course-id ID [--json]

Reads courses/{id}/handoffs/*.md, parses YAML frontmatter for
'date' and 'author' fields, and returns the newest handoff.
"""

import argparse
import json
import os
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from canvas_api import validate_course_id


def _parse_frontmatter(text: str) -> dict:
    """Extract YAML-style frontmatter fields from markdown."""
    fields = {}
    match = re.match(r"^---\s*\n(.*?)\n---", text, re.DOTALL)
    if not match:
        return fields
    for line in match.group(1).splitlines():
        if ":" in line:
            _pf_key = line.split(":", 1)
            key = _pf_key[0].strip() if _pf_key else ""
            val = _pf_key[1].strip() if len(_pf_key) > 1 else ""
            fields[key.strip()] = val.strip()
    return fields


def find_newest_handoff(course_id: str) -> dict | None:
    """Return info about the newest handoff, or None if none exist."""
    handoffs_dir = Path("courses") / str(course_id) / "handoffs"
    if not handoffs_dir.is_dir():
        return None

    candidates = sorted(handoffs_dir.glob("*.md"), reverse=True)
    if not candidates:
        return None

    # Pick newest by filename (handoff_YYYYMMDD.md sorts lexicographically)
    newest = candidates[0]
    try:
        text = newest.read_text(encoding="utf-8")
    except OSError:
        return None

    fm = _parse_frontmatter(text)
    date = fm.get("date") or fm.get("generated") or ""
    author = fm.get("author") or fm.get("by") or fm.get("generated_by") or "Unknown"

    return {"path": str(newest), "date": date, "author": author}


def main():
    parser = argparse.ArgumentParser(description="List handoff docs for a course.")
    parser.add_argument("--course-id", required=True, help="Canvas course ID")
    parser.add_argument("--json", action="store_true", dest="as_json",
                        help="Output as JSON")
    args = parser.parse_args()
    if getattr(args, 'course_id', None) is not None:
        try:
            args.course_id = validate_course_id(args.course_id)
        except ValueError as exc:
            print(f'ERROR: {exc}', file=sys.stderr)
            sys.exit(1)

    result = find_newest_handoff(args.course_id)

    if args.as_json:
        print(json.dumps(result, indent=2))
    elif result:
        print(f"Latest handoff: {result['path']}")
        print(f"Generated: {result['date']}")
        print(f"By: {result['author']}")
    else:
        print("(no handoffs)")


if __name__ == "__main__":
    main()
