#!/usr/bin/env python3
"""Create a change fragment with a collision-free ID.

ID format:  CHG-YYYYMMDD-DEV-NN
  YYYYMMDD  today (UTC)
  DEV       your developer code from RULEFOLDER/TEAM.md
  NN        your own sequence for that day (01, 02, ...)

Three developers working offline on the same day get CHG-20260924-RG-01,
CHG-20260924-AH-01 and CHG-20260924-MK-01. Nothing to coordinate, nothing to
renumber, and the ID tells you when and by whom.

Usage:
  python RULEFOLDER/tools/new_change.py "Add bulk publish endpoint" --type feature --scope api web-ui
  python RULEFOLDER/tools/new_change.py "Fix upload timeout" --type bugfix --scope infra --author AH
"""
import argparse
import datetime
import os
import re
import subprocess
import sys

from _fragments import CHANGES, TYPES, SCOPES, read_team


def resolve_author(explicit):
    if explicit:
        return explicit.upper()
    if os.environ.get("DEV_CODE"):
        return os.environ["DEV_CODE"].upper()
    by_email, _ = read_team()
    try:
        email = subprocess.check_output(["git", "config", "user.email"], text=True).strip().lower()
    except Exception:
        email = ""
    if email in by_email:
        return by_email[email]
    sys.exit(
        "Cannot resolve your developer code. Add your git email to RULEFOLDER/TEAM.md, "
        "or pass --author XX, or set DEV_CODE=XX."
    )


def next_seq(date_compact, dev):
    pat = re.compile(r"^CHG-" + date_compact + "-" + dev + r"-(\d{2})")
    seqs = []
    for p in CHANGES.glob("*.md"):
        m = pat.match(p.name)
        if m:
            seqs.append(int(m.group(1)))
    return max(seqs, default=0) + 1


def slugify(title):
    s = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
    return s[:60] or "change"


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("title")
    ap.add_argument("--type", required=True, choices=TYPES)
    ap.add_argument("--scope", nargs="+", required=True, choices=SCOPES)
    ap.add_argument("--author", help="developer code (overrides git email lookup)")
    ap.add_argument("--date", help="YYYY-MM-DD (default: today UTC)")
    args = ap.parse_args()

    dev = resolve_author(args.author)
    _, names = read_team()
    if dev not in names:
        sys.exit(f"Developer code {dev} is not registered in RULEFOLDER/TEAM.md. Register first.")

    date = args.date or datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
    compact = date.replace("-", "")
    seq = next_seq(compact, dev)
    cid = f"CHG-{compact}-{dev}-{seq:02d}"
    path = CHANGES / f"{cid}-{slugify(args.title)}.md"

    template = (CHANGES / "_TEMPLATE.md").read_text(encoding="utf-8")
    text = (
        template.replace("{{ID}}", cid)
        .replace("{{TITLE}}", args.title)
        .replace("{{DATE}}", date)
        .replace("{{AUTHOR}}", dev)
        .replace("{{TYPE}}", args.type)
        .replace("{{SCOPE}}", "[" + ", ".join(args.scope) + "]")
    )
    path.write_text(text, encoding="utf-8", newline="\n")
    print(cid)
    print(path)
    print("Fill every section, then commit with message:", f"{cid}: {args.title}")


if __name__ == "__main__":
    main()
