#!/usr/bin/env python3
"""Sources: everything that changed since a date, as one markdown digest.

    bin/sources                     the last 7 days
    bin/sources --since 2026-10-01  from that day

Prints to stdout, in markdown, ready to paste into log/YYYY-MM-DD.md:

    1. the standings table (bin/standings)
    2. the session digest (bin/sessions --since), only when config.json
       `read_sessions` is true (off until the user switches it on)
    3. GitHub events for each account in config.json `github_accounts`,
       grouped by repo and day (gh api, read-only)
    4. git log --since for every repo Argoni sees (config.json `repos_folders`
       and `repos`, found fresh each run, see bin/standings)

In a demo folder (`demo: true`) it prints NOT ESTABLISHED for every part
that reads this Mac or the network (sessions, GitHub, git logs) and runs only
bin/standings, which reads the repos the demo lists (none for Alex).

Nothing here writes anywhere. Every command it runs is a read.

Exit status: 0 when it ran; a sub-tool's own failure is reported in the text,
not in the exit code, because the digest is the product.
"""
import datetime
import json
import os
import re
import subprocess
import sys

BIN = os.path.dirname(os.path.abspath(__file__))
sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts
sys.path.insert(0, BIN)
import lifecfg  # noqa: E402


def run(cmd, timeout=120, **kw):
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, **kw)
    except (OSError, subprocess.TimeoutExpired) as e:
        return 1, "", "%s: %s" % (cmd[0], e)
    return p.returncode, p.stdout, p.stderr


def local_repos():
    return lifecfg.repos()


def fence(text):
    return "```\n%s\n```" % text.rstrip()


def gh_events(user, since):
    code, out, err = run(["gh", "api", "users/%s/events?per_page=100" % user])
    if code != 0:
        return "gh api failed: %s" % (err.strip() or "no output")
    try:
        events = json.loads(out)
    except ValueError:
        return "gh api returned something that is not JSON"
    groups = {}
    for e in events:
        day = (e.get("created_at") or "")[:10]
        if day < since:
            continue
        repo = (e.get("repo") or {}).get("name", "?")
        kind = e.get("type", "?").replace("Event", "")
        groups.setdefault(repo, {}).setdefault(day, {}).setdefault(kind, 0)
        groups[repo][day][kind] += 1
    if not groups:
        return "no public events since %s (the API returns the last 100 events, at most 90 days)" % since
    lines = []
    for repo in sorted(groups):
        lines.append("- **%s**" % repo)
        for day in sorted(groups[repo], reverse=True):
            kinds = ", ".join("%s x%d" % (k, n) for k, n in sorted(groups[repo][day].items()))
            lines.append("  - %s: %s" % (day, kinds))
    return "\n".join(lines)


def git_logs(cfg, since):
    found, skipped = local_repos()
    parts = ["- %s" % line for line in skipped]
    for repo in found:
        name = os.path.basename(repo.rstrip("/"))
        code, out, err = lifecfg.git(repo, "log", "--since=%s" % since,
                                     "--format=%cs %h %s", "--no-merges", timeout=120)
        if code != 0:
            parts.append("- **%s**: %s" % (name, err.strip().splitlines()[0] if err.strip() else "git failed"))
            continue
        commits = out.strip().splitlines()
        if not commits:
            parts.append("- **%s**: no commits" % name)
        else:
            parts.append("- **%s**: %d commit(s)" % (name, len(commits)))
            parts.extend("  - %s" % c for c in commits)
    return "\n".join(parts) if parts else "no repos found in config.json `repos_folders` or `repos`"


def main(argv):
    args = argv[1:]
    since = None
    if "--since" in args:
        i = args.index("--since")
        since = args[i + 1] if i + 1 < len(args) else None
        if not since or not re.match(r"^\d{4}-\d{2}-\d{2}$", since):
            print("usage: bin/sources [--since YYYY-MM-DD]", file=sys.stderr)
            return 2
    if since is None:
        since = (datetime.date.today() - datetime.timedelta(days=7)).isoformat()
    cfg = lifecfg.config()
    demo = lifecfg.demo()
    today = datetime.date.today().isoformat()

    print("# What changed since %s (as of %s)\n" % (since, today))

    print("## Standings\n")
    cmd = [sys.executable, os.path.join(BIN, "standings")]
    code, out, err = run(cmd)
    print(fence(out + err))
    print()

    if demo:
        print("## Sessions, GitHub, commits\n")
        print("NOT ESTABLISHED: a demo folder; this Mac's sessions, GitHub and repos are not read.")
        return 0

    print("## Sessions since %s\n" % since)
    if cfg.get("read_sessions"):
        cmd = [sys.executable, os.path.join(BIN, "sessions"), "--since", since, "--codex"]
        code, out, err = run(cmd, timeout=300)
        print(fence(out + err))
    else:
        print("not read: AI chats are off for the digests (switch them on in settings: read_sessions)")
    print()

    logins = [a["login"] for a in cfg["github_accounts"] if a.get("login")]
    if not logins:
        print("## GitHub events\n")
        print("no accounts in config.json `github_accounts`")
        print()
    for user in logins:
        print("## GitHub events for %s since %s\n" % (user, since))
        print(gh_events(user, since))
        print()

    print("## Commits since %s\n" % since)
    print(git_logs(cfg, since))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
