"""Mac Wrapped: a Spotify-Wrapped-style look at how you use your Mac.

Privacy: this never reads pages, messages, code or prompts. It counts app open/close times, website domains,
meeting times (never titles), git commit dates, file types and project names (never code), the first word of
each shell command (git, npm...), Claude Code session times (never prompts), and a checkup of battery, memory
and disk, and it ranks the artists and songs in your Mac's now-playing log. Nothing is uploaded. Dating and
health apps count toward your time but their names never show.

Usage (Terminal needs Full Disk Access: System Settings > Privacy & Security):
    python3 wrapped.py                 # opens your Wrapped in the browser
    python3 wrapped.py --code ~/work   # also look for git repos here (default: common code folders)
    python3 wrapped.py --no-open --out mac_stats.json

macOS keeps about four weeks of app use, so app time is "the last four weeks". Meetings, code
and Claude Code cover the full year.
"""
import argparse
import base64
import json
import os
import re
import shutil
import statistics
import sqlite3
import struct
import subprocess
import tempfile
import webbrowser
from collections import Counter
from datetime import datetime, timedelta, timezone
from pathlib import Path
from urllib.parse import urlparse

HOME = Path.home()
APPLE_EPOCH = datetime(2001, 1, 1, tzinfo=timezone.utc)
CHROME_EPOCH = datetime(1601, 1, 1, tzinfo=timezone.utc)
STUDIO_URL = "https://eliotcbrown.com/mac-wrapped/"
YEAR = timedelta(days=365)
WEB_WINDOW = timedelta(days=90)        # Chrome keeps about 90 days of history
MAX_SESSION = timedelta(hours=4)       # longer "sessions" are a screen left on
PRIVATE_APP = re.compile(r"hinge|tinder|bumble|grindr|feeld|okcupid|coffeemeetsbagel|flohealth|betterhelp|talkspace|onlyfans", re.I)   # time counts, the name never shows
PRIVATE_SITE = re.compile(r"hinge\.co|tinder|bumble\.com|grindr|okcupid|onlyfans|pornhub|xvideos|xnxx|xhamster|redtube|youporn|betterhelp|talkspace", re.I)
SCREENSHOT = re.compile(r"(Screenshot|Screen Shot|Screen Recording)")
MIN_PLAYS = 20                         # fewer songs than this isn't a taste
FOCUS_STRETCH = 25 * 60                # 25 minutes in one app counts as focus
PAIR_GAP = 10 * 60                     # a switch after a longer break is not a bounce
LATE = lambda h: h >= 22 or h < 4      # noqa: E731
SYSTEM_APPS = re.compile(r"^(com\.apple\.(springboard|SpringBoard|loginwindow|ScreenSaver|Spotlight|controlcenter|notificationcenterui|"
                         r"UserNotificationCenter|dock|InCallService|PassbookUIService|CoreAuthUI|SecurityAgent|screencaptureui|"
                         r"ScreenContinuity|WindowManager|accessibility|siri|Siri|AuthKitUIService|SharingViewService|"
                         r"datadetectors|mobilecal\.widget|PosterBoard|InputUI|universalcontrol|ClockAngel|clockangel|mobiletimer\.alarm|camera\.lockscreen)|SB[A-Z])")
APP_NAMES = {
    "com.burbn.instagram": "Instagram", "com.zhiliaoapp.musically": "TikTok", "com.atebits.Tweetie2": "X",
    "com.reddit.Reddit": "Reddit", "com.google.ios.youtube": "YouTube", "com.toyopagroup.picaboo": "Snapchat",
    "com.facebook.Facebook": "Facebook", "com.burbn.barcelona": "Threads", "com.linkedin.LinkedIn": "LinkedIn",
    "com.apple.MobileSMS": "Messages", "net.whatsapp.WhatsApp": "WhatsApp", "ph.telegra.Telegraph": "Telegram",
    "org.whispersystems.signal": "Signal", "com.facebook.Messenger": "Messenger", "com.hammerandchisel.discord": "Discord",
    "com.tinyspeck.chatlyio": "Slack", "com.spotify.client": "Spotify", "com.apple.Music": "Music",
    "com.apple.mobilesafari": "Safari", "com.google.chrome.ios": "Chrome", "com.apple.mobilemail": "Mail",
    "com.google.Gmail": "Gmail", "com.apple.mobilephone": "Phone", "com.apple.facetime": "FaceTime",
    "com.apple.camera": "Camera", "com.apple.mobileslideshow": "Photos", "com.apple.Maps": "Maps",
    "com.google.Maps": "Google Maps", "com.apple.findmy": "Find My", "com.apple.Preferences": "Settings",
    "com.apple.mobilenotes": "Notes", "com.apple.reminders": "Reminders", "com.apple.mobilecal": "Calendar",
    "com.apple.Health": "Health", "com.apple.mobiletimer": "Clock", "com.apple.calculator": "Calculator",
    "com.apple.podcasts": "Podcasts", "com.apple.news": "News", "com.apple.tv": "TV", "com.apple.Fitness": "Fitness",
    "com.apple.shortcuts": "Shortcuts", "com.apple.DocumentsApp": "Files", "com.apple.Passbook": "Wallet",
    "com.apple.VoiceMemos": "Voice Memos", "com.apple.journal": "Journal", "com.apple.freeform": "Freeform", "com.apple.weather": "Weather", "com.apple.AppStore": "App Store",
    "com.ubercab.UberClient": "Uber", "com.zimride.instant": "Lyft", "com.anthropic.claude": "Claude",
    "com.openai.chat": "ChatGPT", "com.netflix.Netflix": "Netflix", "com.amazon.Amazon": "Amazon",
    "com.venmo.touch.v2": "Venmo", "com.hinge.mobile": "Hinge", "com.cardify.tinder": "Tinder",
    "com.google.Chrome": "Chrome", "com.apple.Safari": "Safari", "com.mitchellh.ghostty": "Ghostty",
    "com.microsoft.VSCode": "Visual Studio Code", "com.todesktop.230313mzl4w4u92": "Cursor", "com.apple.Terminal": "Terminal",
    "com.googlecode.iterm2": "iTerm", "com.apple.dt.Xcode": "Xcode", "com.apple.finder": "Finder", "com.apple.mail": "Mail",
    "com.figma.Desktop": "Figma", "notion.id": "Notion", "com.linear": "Linear", "com.apple.iChat": "Messages",
}


# ---------- shared helpers ----------
def copy_db(path):
    """Open a read-only copy (with its -wal/-shm), so a running app is never touched."""
    src = Path(path)
    tmp = Path(tempfile.mkdtemp(prefix="phonewrapped-"))
    for suffix in ("", "-wal", "-shm"):
        f = Path(str(src) + suffix)
        if f.exists():
            shutil.copy2(f, tmp / f.name)
    return sqlite3.connect(f"file:{tmp / src.name}?mode=ro", uri=True), tmp


def query(path, sql, args=()):
    con, tmp = copy_db(path)
    try:
        return con.execute(sql, args).fetchall()
    finally:
        con.close()
        shutil.rmtree(tmp, ignore_errors=True)


def apple_time(ts):
    secs = ts / 1e9 if ts > 1e11 else ts
    return (APPLE_EPOCH + timedelta(seconds=secs)).astimezone()


def top(counter, n=5):
    return counter.most_common(n)


def app_name(bundle, cache={}):  # noqa: B006 - deliberate per-run cache
    if bundle in APP_NAMES:
        return APP_NAMES[bundle]
    if bundle not in cache:
        found = subprocess.run(["mdfind", f"kMDItemCFBundleIdentifier == '{bundle}'"], capture_output=True, text=True).stdout.split("\n")[0]
        cache[bundle] = Path(found).stem if found.endswith(".app") else bundle.split(".")[-1].replace("-", " ").title()
    return cache[bundle]


# ---------- music: the now-playing log keeps about a month of songs ----------
MUSIC_APPS = (b"com.spotify.client", b"com.apple.Music")
TWO_PART_ARTISTS = {"Tyler, The Creator", "Earth, Wind & Fire"}


def tagged_text(window, tag):
    """The last length-prefixed text with this protobuf tag in a slice of a Biome record."""
    found = None
    for i in range(len(window) - 2):
        if window[i] == tag and 0 < window[i + 1] <= len(window) - i - 2:
            try:
                text = window[i + 2:i + 2 + window[i + 1]].decode()
            except UnicodeDecodeError:
                continue
            if text.isprintable():
                found = text
    return found


def record_time(window):
    """The nearest Apple-epoch timestamp before a record's text fields."""
    found = None
    for i in range(len(window) - 8):
        v = struct.unpack("<d", window[i:i + 8])[0]
        if 6e8 < v < 9e8:
            found = v
    return found


def nowplaying_plays(folder):
    """(time, song, artist) per song change. The log repeats a song on every pause and resume, so repeats in a row count once."""
    rows = []
    for root, _, files in os.walk(folder):
        for f in files:
            if f == "lock":
                continue
            data = Path(root, f).read_bytes()
            for app in MUSIC_APPS:
                for m in re.finditer(re.escape(app), data):
                    near = data[max(0, m.start() - 110):m.start()]
                    title = None
                    for i in range(len(near) - 2):   # the song title: tag 0x42, ending just before the app id
                        n = near[i + 1]
                        if near[i] == 0x42 and n and i + 2 + n <= len(near) and len(near) - (i + 2 + n) <= 50:
                            try:
                                title = near[i + 2:i + 2 + n].decode()
                            except UnicodeDecodeError:
                                continue
                            if title.isprintable():
                                break
                            title = None
                    t = record_time(data[max(0, m.start() - 420):m.start()])
                    if title and t:
                        rows.append((t, title, tagged_text(data[max(0, m.start() - 300):m.start()], 0x2a)))
    plays, last = [], None
    for row in sorted(rows):
        if row[1:] != last:
            plays.append(row)
        last = row[1:]
    return plays


def primary_artist(artist):
    return artist if artist in TWO_PART_ARTISTS else artist.split(", ")[0]


def music_stats(plays):
    """Rankings only: the log overcounts plays, so no play counts leave this function."""
    plays = [(t, s, primary_artist(a)) for t, s, a in plays if a and not a.startswith("Listening on")]
    if len(plays) < MIN_PLAYS:
        return None
    artists = Counter(a for _, _, a in plays)
    songs = Counter((s, a) for _, s, a in plays)
    return {
        "days": len({apple_time(t).date() for t, _, _ in plays}),
        "artists": len(artists),
        "songs": len(songs),
        "top_artists": [a for a, _ in artists.most_common(5)],
        "top_song": {"name": songs.most_common(1)[0][0][0], "artist": songs.most_common(1)[0][0][1]},
        "peak_hour": Counter(apple_time(t).hour for t, _, _ in plays).most_common(1)[0][0],
    }


def shareable_sites(visits):
    return Counter({d: n for d, n in visits.items() if not PRIVATE_SITE.search(d)})


def music():
    folder = HOME / "Library/Biome/streams/restricted/Media.NowPlaying/local"
    return music_stats(nowplaying_plays(folder)) if folder.exists() else None


# ---------- websites: every Chrome profile, plus Safari ----------
def domain(url):
    host = (urlparse(url).hostname or "").lower()
    return host[4:] if host.startswith("www.") else host


def websites(now):
    since = now - WEB_WINDOW
    visits, profiles = Counter(), 0
    chrome_since = int((since - CHROME_EPOCH).total_seconds() * 1e6)
    for hist in (HOME / "Library/Application Support/Google/Chrome").glob("*/History"):
        # Count pages people opened: skip redirects and frames inside pages (Chrome's transition flags).
        rows = query(hist, """SELECT u.url FROM visits v JOIN urls u ON u.id = v.url
                              WHERE v.visit_time > ? AND (v.transition & 0xC0000000) = 0 AND (v.transition & 0xFF) NOT IN (3, 4)""",
                     (chrome_since,))
        if len(rows) >= 50:
            profiles += 1
        visits.update(domain(u) for (u,) in rows)
    safari = HOME / "Library/Safari/History.db"
    if safari.exists():
        rows = query(safari, """SELECT i.url FROM history_visits v JOIN history_items i ON i.id = v.history_item
                                WHERE v.visit_time > ? AND v.redirect_source IS NULL""",
                     ((since - APPLE_EPOCH).total_seconds(),))
        visits.update(domain(u) for (u,) in rows)
    for junk in ("", "localhost", "127.0.0.1", "newtab"):
        visits.pop(junk, None)
    if not visits:
        return None
    total = sum(visits.values())
    return {"days": WEB_WINDOW.days, "pages_per_day": round(total / WEB_WINDOW.days), "sites": len(visits),
            "chrome_profiles": profiles, "top_sites": [{"name": d, "visits": n} for d, n in top(shareable_sites(visits))], "_all": visits}


CODE_DIRS = ["Developer", "code", "Code", "Projects", "projects", "src", "GitHub", "repos", "dev", "work", "Documents/GitHub"]
LANGS = {".py": "Python", ".ts": "TypeScript", ".tsx": "TypeScript", ".js": "JavaScript", ".jsx": "JavaScript", ".mjs": "JavaScript",
         ".cjs": "JavaScript", ".go": "Go", ".rs": "Rust", ".swift": "Swift", ".kt": "Kotlin", ".java": "Java", ".rb": "Ruby",
         ".php": "PHP", ".c": "C", ".h": "C", ".cpp": "C++", ".cc": "C++", ".cs": "C#", ".html": "HTML", ".css": "CSS",
         ".scss": "CSS", ".sql": "SQL", ".sh": "Shell", ".md": "Markdown", ".ipynb": "Jupyter", ".vue": "Vue", ".svelte": "Svelte",
         ".dart": "Dart", ".ex": "Elixir", ".scala": "Scala", ".r": "R", ".lua": "Lua"}
TERMINALS = {"Ghostty", "Terminal", "iTerm", "Warp", "Alacritty", "kitty", "WezTerm"}
GENERATED_LINES = 5000   # one file gaining more lines than this in a commit is generated or vendored
WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]


# ---------- apps: Biome's App.InFocus stream for this Mac ----------
INFOCUS = re.compile(rb"\x10[\x00\x01]\x18([\x00\x01])\x21(.{8})\x32(.)", re.S)


def infocus_events(folder):
    """(time, bundle, started) from Biome SEGB files: small protobuf records, parsed by their field tags."""
    events = set()
    for root, _, files in os.walk(folder):
        for f in files:
            if f == "lock":
                continue
            data = Path(root, f).read_bytes()
            for m in INFOCUS.finditer(data):
                t = struct.unpack("<d", m.group(2))[0]
                bundle = data[m.end():m.end() + m.group(3)[0]]
                if 6e8 < t < 9e8 and re.fullmatch(rb"[A-Za-z0-9.\-_]+", bundle):
                    events.add((t, bundle.decode(), m.group(1) == b"\x01"))
    return sorted(events)


def is_real_app(bundle, cache={}):  # noqa: B006 - per-run cache
    if not bundle.startswith("com.apple.") or bundle in APP_NAMES:
        return True
    if bundle not in cache:
        cache[bundle] = bool(subprocess.run(["mdfind", f"kMDItemCFBundleIdentifier == '{bundle}'"], capture_output=True, text=True).stdout.strip())
    return cache[bundle]


def focus_stats(sess, days):
    """How attention moves: sess is (start, seconds, app), sorted by start."""
    pairs, per_day = Counter(), Counter()
    for a, b in zip(sess, sess[1:]):
        if a[2] != b[2] and (b[0] - a[0]).total_seconds() < PAIR_GAP:
            pairs[tuple(sorted((a[2], b[2])))] += 1
    for start, secs, _ in sess:
        per_day[start.date()] += secs
    weekday = [v for d, v in per_day.items() if d.weekday() < 5]
    weekend = [v for d, v in per_day.items() if d.weekday() >= 5]
    pair = pairs.most_common(1)[0] if pairs else None
    return {
        "median_focus_sec": round(statistics.median(s for _, s, _ in sess)),
        "focus_stretches_per_day": round(sum(1 for _, s, _ in sess if s >= FOCUS_STRETCH) / days, 1),
        "top_pair": {"apps": list(pair[0]), "per_day": round(pair[1] / days)} if pair else None,
        "days_used": len(per_day),
        "weekday_hours": round(sum(weekday) / len(weekday) / 3600, 1) if weekday else None,
        "weekend_hours": round(sum(weekend) / len(weekend) / 3600, 1) if weekend else None,
    }


def mac_apps():
    folder = HOME / "Library/Biome/streams/restricted/App.InFocus/local"
    if not folder.exists():
        return None
    opened, sess, hidden = {}, [], 0
    for t, bundle, started in infocus_events(folder):
        if started:
            opened[bundle] = t
        elif bundle in opened:
            start = opened.pop(bundle)
            if 0 < t - start < MAX_SESSION.total_seconds() and not SYSTEM_APPS.match(bundle) and is_real_app(bundle):
                if PRIVATE_APP.search(bundle):
                    hidden += t - start
                else:
                    sess.append((apple_time(start), t - start, app_name(bundle)))
    if not sess:
        return None
    sess.sort(key=lambda x: x[0])
    days = (sess[-1][0].date() - sess[0][0].date()).days + 1
    by_app, by_hour, by_day = Counter(), Counter(), Counter()
    for start, secs, name in sess:
        by_app[name] += secs
        by_hour[start.hour] += secs
        by_day[start.weekday()] += secs
    total = sum(by_app.values()) + hidden
    return {
        **focus_stats(sess, days),
        "days": days, "hours_per_day": round(total / 3600 / days, 1), "total_hours": round(total / 3600),
        "top_apps": [{"name": n, "hours": round(s / 3600, 1), "share_pct": round(100 * s / total, 1)} for n, s in top(by_app)],
        "apps_used": len(by_app), "busiest_hour": by_hour.most_common(1)[0][0], "busiest_weekday": WEEKDAYS[by_day.most_common(1)[0][0]],
        "late_night_pct": round(100 * sum(v for h, v in by_hour.items() if LATE(h)) / total, 1),
        "switches_per_day": round(len(sess) / days),
        "terminal_pct": round(sum(a for n, a in by_app.items() if n in TERMINALS) * 100 / total, 1),
        "by_hour": [round(by_hour.get(h, 0) / 3600 / days, 2) for h in range(24)],   # average hours in each hour of the day
    }


SITE_KINDS = [
    ("AI", r"(^|\.)(claude\.ai|chatgpt\.com|openai\.com|anthropic\.com|perplexity\.ai|gemini\.google\.com|poe\.com|grok\.com|huggingface\.co|cursor\.com|v0\.dev|lovable\.dev)$"),
    ("Dev", r"(^|\.)(github\.com|gitlab\.com|stackoverflow\.com|vercel\.com|npmjs\.com|localhost|console\.cloud\.google\.com|aws\.amazon\.com|supabase\.com|developer\.apple\.com|docs\..*)$"),
    ("Work", r"(^|\.)(linear\.app|notion\.so|slack\.com|mail\.google\.com|docs\.google\.com|drive\.google\.com|calendar\.google\.com|figma\.com|atlassian\.net|zoom\.us|meet\.google\.com|airtable\.com|hubspot\.com|substack\.com|stripe\.com)$"),
    ("Social", r"(^|\.)(linkedin\.com|x\.com|twitter\.com|instagram\.com|facebook\.com|reddit\.com|threads\.net|tiktok\.com|news\.ycombinator\.com|discord\.com)$"),
    ("Video", r"(^|\.)(youtube\.com|netflix\.com|twitch\.tv|vimeo\.com|hulu\.com|max\.com|disneyplus\.com|primevideo\.com)$"),
    ("Shopping", r"(^|\.)(amazon\.com|ebay\.com|etsy\.com|shopify\.com|target\.com|walmart\.com)$"),
    ("Search", r"(^|\.)(google\.com|bing\.com|duckduckgo\.com|kagi\.com)$"),
]


def site_kinds(web):
    """Where browsing goes, by kind of site. Unrecognised sites count as Other."""
    kinds, ai = Counter(), Counter()
    for name, visits in web.pop("_all").items():
        kind = next((k for k, rx in SITE_KINDS if re.search(rx, name)), "Other")
        kinds[kind] += visits
        if kind == "AI":
            ai[name] += visits
    total = sum(kinds.values()) or 1
    web["kinds"] = [{"name": k, "share_pct": round(100 * v / total, 1)} for k, v in kinds.most_common() if k != "Other"][:5]
    web["ai_visits"] = sum(ai.values())
    web["top_ai"] = ai.most_common(1)[0][0] if ai else None
    return web


# ---------- meetings: Calendar's own database; times only, never titles ----------
def meetings(now):
    db = HOME / "Library/Group Containers/group.com.apple.calendar/Calendar.sqlitedb"
    if not db.exists():
        return None
    since, until = (now - YEAR - APPLE_EPOCH).total_seconds(), (now - APPLE_EPOCH).total_seconds()
    rows = query(db, """
        SELECT o.occurrence_date, c.end_date - c.start_date FROM OccurrenceCache o JOIN CalendarItem c ON c.ROWID = o.event_id
        WHERE c.all_day = 0 AND c.has_attendees = 1 AND COALESCE(c.invitation_status, 0) != 2
          AND o.occurrence_date > ? AND o.occurrence_date < ? AND c.end_date - c.start_date BETWEEN 300 AND 14400""", (since, until))
    if not rows:
        return None
    starts = [apple_time(t) for t, _ in rows]
    hours = sum(d for _, d in rows) / 3600
    weeks = Counter(s.isocalendar()[:2] for s in starts)
    return {
        "meetings": len(rows), "hours": round(hours), "hours_per_week": round(hours / 52, 1),
        "longest_min": round(max(d for _, d in rows) / 60),
        "busiest_weekday": WEEKDAYS[Counter(s.weekday() for s in starts).most_common(1)[0][0]],
        "busiest_week_meetings": weeks.most_common(1)[0][1],
        "busiest_hour": Counter(s.hour for s in starts).most_common(1)[0][0],
    }


# ---------- code: your own git commits this year; dates, counts and file types, never code ----------
def find_repos(roots):
    repos = []
    for root in roots:
        for dirpath, dirnames, _ in os.walk(root):
            depth = Path(dirpath).relative_to(root).parts
            if ".git" in dirnames:
                repos.append(Path(dirpath))
                dirnames.clear()
            elif len(depth) >= 3 or Path(dirpath).name in ("node_modules", ".venv", "venv", "Library"):
                dirnames.clear()
    return repos


def my_emails():
    out = subprocess.run(["git", "config", "--global", "--get-all", "user.email"], capture_output=True, text=True).stdout.split()
    return {e.lower() for e in out}


def has_git():
    """Without Apple's developer tools, /usr/bin/git only pops up an install prompt; skip code then."""
    return subprocess.run(["xcode-select", "-p"], capture_output=True).returncode == 0


def code(now, extra):
    if not has_git():
        return None
    roots = [HOME / d for d in CODE_DIRS if (HOME / d).exists()] + [Path(p).expanduser() for p in extra]
    emails = my_emails()
    commits, added, removed, langs, hours, days = 0, 0, 0, Counter(), Counter(), set()
    per_repo, started = Counter(), 0
    for repo in find_repos(roots):
        local = subprocess.run(["git", "-C", str(repo), "config", "user.email"], capture_output=True, text=True).stdout.strip().lower()
        mine = emails | ({local} if local else set())
        log = subprocess.run(["git", "-C", str(repo), "log", "--all", "--no-merges", f"--since={(now - YEAR).isoformat()}",
                              "--pretty=format:@%ae\t%at", "--numstat"], capture_output=True, text=True).stdout
        n0 = commits
        me = False
        for line in log.splitlines():
            if line.startswith("@"):
                email, ts = line[1:].split("\t")
                me = email.lower() in mine
                if me:
                    commits += 1
                    t = datetime.fromtimestamp(int(ts)).astimezone()
                    hours[t.hour] += 1
                    days.add(t.date())
            elif me and line.strip():
                a, r, path = (line.split("\t") + ["", ""])[:3]
                lang = LANGS.get(Path(path).suffix.lower())
                if lang and a.isdigit() and r.isdigit() and int(a) <= GENERATED_LINES and "/dist/" not in path and "lock" not in path:
                    added, removed = added + int(a), removed + int(r)
                    langs[lang] += int(a)
        if commits > n0:
            per_repo[repo.name] += commits - n0
            first = subprocess.run(["git", "-C", str(repo), "log", "--all", "--reverse", "--format=%at"], capture_output=True, text=True).stdout.split("\n", 1)[0]
            started += first.isdigit() and int(first) > (now - YEAR).timestamp()
    if not commits:
        return None
    total_lines = sum(langs.values()) or 1
    return {
        "commits": commits, "repos": len(per_repo), "new_projects": started,
        "top_projects": [{"name": n, "commits": c} for n, c in top(per_repo)], "lines_added": added, "lines_removed": removed, "days_coding": len(days),
        "top_languages": [{"name": n, "share_pct": round(100 * v / total_lines, 1)} for n, v in langs.most_common(3)],
        "busiest_hour": hours.most_common(1)[0][0],
        "late_night_pct": round(100 * sum(v for h, v in hours.items() if LATE(h)) / commits, 1),
    }


# ---------- terminal: the first word of each command in your shell history ----------
def terminal():
    files = [HOME / ".zsh_history", HOME / ".bash_history"]
    words = Counter()
    for f in files:
        if not f.exists():
            continue
        for line in f.read_bytes().decode("utf-8", "ignore").splitlines():
            cmd = line.split(";", 1)[1] if line.startswith(": ") and ";" in line else line
            first = cmd.strip().split(" ")[0] if cmd.strip() else ""
            first = first.split("/")[-1]
            if re.fullmatch(r"[A-Za-z][A-Za-z0-9_+-]{0,24}", first):   # no paths or script.sh names
                words[first] += 1
    total = sum(words.values())
    if total < 50:
        return None
    return {"commands": total, "distinct": len(words),
            "top_commands": [{"name": w, "share_pct": round(100 * c / total, 1)} for w, c in top(words)]}


# ---------- Claude Code: session times from its local transcripts, never what was said ----------
def claude_code(now):
    root = HOME / ".claude/projects"
    if not root.exists():
        return None
    since = (now - YEAR).timestamp()
    sessions, scripted, prompts, minutes, days, projects = 0, 0, 0, 0.0, Counter(), set()
    for f in root.glob("*/*.jsonl"):
        if f.stat().st_mtime < since:
            continue
        stamps, n_prompts, sdk = [], 0, False
        for line in f.open(encoding="utf-8", errors="ignore"):
            try:
                rec = json.loads(line)
            except ValueError:
                continue
            sdk = sdk or rec.get("entrypoint") == "sdk-cli"
            ts = rec.get("timestamp")
            if ts:
                stamps.append(datetime.fromisoformat(ts.replace("Z", "+00:00")))
            msg = rec.get("message") or {}
            # A typed prompt: a user record whose content is plain text, not a tool result.
            if rec.get("type") == "user" and not rec.get("isMeta") and isinstance(msg.get("content"), str):
                n_prompts += 1
        if not stamps or not n_prompts:
            continue
        if sdk:   # started by a script (claude -p, the SDK), not typed by you
            scripted += 1
            continue
        sessions += 1
        prompts += n_prompts
        projects.add(f.parent.name)
        stamps.sort()
        active = sum(min((b - a).total_seconds(), 600) for a, b in zip(stamps, stamps[1:]))  # gaps over 10 min aren't work
        minutes += active / 60
        days[stamps[0].astimezone().date()] += 1
    if not sessions:
        return None
    best_day, best = days.most_common(1)[0]
    return {"since": min(days).isoformat(), "sessions": sessions, "scripted_runs": scripted, "prompts": prompts, "hours": round(minutes / 60), "projects": len(projects),
            "days_used": len(days), "busiest_day": best_day.isoformat(), "busiest_day_sessions": best}


# ---------- downloads ----------
def desktop():
    folder = HOME / "Desktop"
    names = [f.name for f in folder.iterdir() if not f.name.startswith(".")] if folder.exists() else []
    return {"items": len(names), "screenshots": sum(1 for n in names if SCREENSHOT.match(n))} if names else None


def downloads(now):
    folder = HOME / "Downloads"
    since = (now - YEAR).timestamp()
    files = [f for f in folder.iterdir() if f.stat().st_mtime > since] if folder.exists() else []
    if not files:
        return None
    size = sum(f.stat().st_size for f in files if f.is_file())
    kinds = Counter(f.suffix.lower().lstrip(".") or "folder" for f in files)
    return {"files": len(files), "gb": round(size / 1e9, 1), "top_kind": kinds.most_common(1)[0][0]}


# ---------- Mac checkup: battery, memory, disk, restarts, and what's eating space ----------
def sh(*cmd):
    return subprocess.run(cmd, capture_output=True, text=True, timeout=120).stdout


def size_gb(path):
    out = sh("du", "-sk", str(path)) if Path(path).exists() else ""
    return round(int(out.split()[0]) / 1048576, 1) if out.strip() else 0.0


def node_modules_gb(extra):
    roots = [HOME / d for d in CODE_DIRS if (HOME / d).exists()] + [Path(p).expanduser() for p in extra]
    found = []
    for root in roots:
        for dirpath, dirnames, _ in os.walk(root):
            if "node_modules" in dirnames:
                found.append(Path(dirpath, "node_modules"))
            depth = len(Path(dirpath).relative_to(root).parts)
            dirnames[:] = [d for d in dirnames if d not in ("node_modules", ".git") and depth < 4]
    return round(sum(size_gb(f) for f in found), 1), len(found)


def checkup(extra):
    out = {"model": sh("sysctl", "-n", "hw.model").strip(), "macos": sh("sw_vers", "-productVersion").strip(),
           "ram_gb": round(int(sh("sysctl", "-n", "hw.memsize")) / 2**30)}
    power = json.loads(sh("system_profiler", "-json", "SPPowerDataType") or "{}").get("SPPowerDataType", [])
    battery = next((x.get("sppower_battery_health_info") for x in power if x.get("_name") == "spbattery_information"), None)
    if battery:
        out["battery_pct"] = int(str(battery.get("sppower_battery_health_maximum_capacity", "0")).rstrip("%") or 0) or None
        out["battery_cycles"] = battery.get("sppower_battery_cycle_count")
    swap = re.search(r"used = ([\d.]+)M", sh("sysctl", "-n", "vm.swapusage"))
    out["swap_gb"] = round(float(swap.group(1)) / 1024, 1) if swap else 0
    by_app = Counter()
    for line in sh("ps", "-axo", "rss=,comm=").splitlines():
        rss, _, cmd = line.strip().partition(" ")
        m = re.search(r"/([^/]+)\.app/", cmd)
        by_app[m.group(1) if m else cmd.split("/")[-1]] += int(rss or 0)
    out["memory_now"] = [{"name": n, "gb": round(k / 2**20, 1)} for n, k in by_app.most_common(3)]
    df = sh("df", "-k", "/System/Volumes/Data").splitlines()[-1].split()
    out["disk_gb"], out["disk_free_gb"] = round(int(df[1]) / 2**20), round(int(df[3]) / 2**20)
    boot = re.search(r"sec = (\d+)", sh("sysctl", "-n", "kern.boottime"))
    out["days_since_restart"] = round((datetime.now().timestamp() - int(boot.group(1))) / 86400) if boot else None
    nm_gb, nm_count = node_modules_gb(extra)
    out["space"] = {k: v for k, v in {
        "node_modules": nm_gb, "Docker": size_gb(HOME / "Library/Containers/com.docker.docker"),
        "Library caches": size_gb(HOME / "Library/Caches"), "Xcode builds": size_gb(HOME / "Library/Developer/Xcode/DerivedData"),
        "iOS simulators": size_gb(HOME / "Library/Developer/CoreSimulator"), "Downloads": size_gb(HOME / "Downloads"),
    }.items() if v >= 1}
    out["node_modules_folders"] = nm_count
    out["tips"] = tips(out)
    return out


def tips(c):
    """Plain fixes, each tied to a number from this Mac."""
    out, space = [], c.get("space", {})
    top_mem = (c.get("memory_now") or [{}])[0]
    if c.get("swap_gb", 0) >= 2:
        extra = f" {top_mem['name']} alone is using about {top_mem['gb']} GB." if top_mem.get("gb", 0) >= 2 else ""
        fix = " In Chrome, turn on Memory Saver (Settings → Performance)." if "Chrome" in top_mem.get("name", "") else " Quit what you aren't using."
        out.append(f"Memory: {c['swap_gb']} GB is spilling to disk (swap), which slows everything.{extra}{fix}")
    if c.get("battery_pct"):
        if c["battery_pct"] < 80:
            out.append(f"Battery: {c['battery_pct']}% of new after {c['battery_cycles']} cycles. Below 80%, Apple recommends service.")
        else:
            out.append(f"Battery: {c['battery_pct']}% of new after {c['battery_cycles']} cycles. Keep Optimized Battery Charging on (System Settings → Battery).")
    if c.get("days_since_restart") and c["days_since_restart"] >= 7:
        out.append(f"Restart: it's been {c['days_since_restart']} days. A restart clears memory leaks and finishes updates.")
    if space.get("node_modules", 0) >= 5:
        out.append(f"node_modules: {space['node_modules']} GB in {c['node_modules_folders']} folders. Clear old ones with `npx npkill`.")
    if space.get("Docker", 0) >= 20:
        out.append(f"Docker: {space['Docker']} GB. `docker system prune` removes stopped containers and unused images.")
    if space.get("Xcode builds", 0) >= 5:
        out.append(f"Xcode: {space['Xcode builds']} GB of build files in DerivedData. Xcode rebuilds them, so old ones can go.")
    if space.get("Downloads", 0) >= 5:
        out.append(f"Downloads: {space['Downloads']} GB. Sort by size and clear the old installers and exports.")
    if c.get("disk_free_gb") is not None and c["disk_free_gb"] < 0.15 * c["disk_gb"]:
        out.append(f"Disk: only {c['disk_free_gb']} GB free of {c['disk_gb']} GB. macOS slows down when it's nearly full.")
    return out[:5]


# ---------- the computer personality ----------
def personality(s):
    mac, web, mt, cd, cc = (s.get(k) or {} for k in ("mac_apps", "web", "meetings", "code", "claude_code"))
    top_app = (mac.get("top_apps") or [{}])[0].get("name")
    candidates = [
        ("The AI Pair Programmer", (cc.get("prompts") or 0) / 5000, f"{cc.get('prompts') or 0:,} prompts to Claude Code."),
        ("The Night Coder", (cd.get("late_night_pct") or 0) / 25 if (cd.get("commits") or 0) > 50 else 0, f"{cd.get('late_night_pct')}% of my commits land after 10 pm."),
        ("The Builder", (cd.get("commits") or 0) / 500, f"{cd.get('commits'):,} commits this year." if cd.get("commits") else ""),
        ("The Meeting Marathoner", (mt.get("hours_per_week") or 0) / 12, f"{mt.get('hours_per_week')} hours of meetings a week."),
        ("The Terminal Dweller", (mac.get("terminal_pct") or 0) / 30, f"{mac.get('terminal_pct')}% of my Mac time is in a terminal."),
        ("The Tab Hoarder", (web.get("pages_per_day") or 0) / 400, f"{web.get('pages_per_day')} web pages a day."),
        ("The Night Owl", (mac.get("late_night_pct") or 0) / 20, f"{mac.get('late_night_pct')}% of my Mac time is after 10 pm."),
        ("The Context Switcher", (mac.get("switches_per_day") or 0) / 300, f"I switch apps {mac.get('switches_per_day')} times a day."),
    ]
    name, score, why = max(candidates, key=lambda c: c[1])
    return {"name": name, "why": why} if score >= 0.8 else {"name": "The All-Rounder", "why": f"Mostly {top_app}, a bit of everything."}


# ---------- run ----------
def run(step, fn, *args):
    try:
        return fn(*args)
    except PermissionError:
        raise SystemExit("macOS blocked access. Give your terminal Full Disk Access "
                         "(System Settings > Privacy & Security > Full Disk Access), reopen it, and rerun.")
    except Exception as e:  # one missing source shouldn't sink the rest
        print(f"  skipped {step}: {type(e).__name__}: {e}")
        return None


def build(code_dirs):
    now = datetime.now().astimezone()
    stats = {"made": now.date().isoformat()}
    stats["mac_apps"] = run("apps", mac_apps)
    web = run("websites", websites, now)
    stats["web"] = site_kinds(web) if web else None
    stats["meetings"] = run("meetings", meetings, now)
    stats["code"] = run("code", code, now, code_dirs)
    stats["terminal"] = run("terminal", terminal)
    stats["claude_code"] = run("claude code", claude_code, now)
    stats["music"] = run("music", music)
    stats["desktop"] = run("desktop", desktop)
    stats["downloads"] = run("downloads", downloads, now)
    stats["checkup"] = run("checkup", checkup, code_dirs)
    stats["personality"] = personality(stats)
    return {k: v for k, v in stats.items() if v is not None}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--code", action="append", default=[], help="another folder to look for git repos in")
    ap.add_argument("--out", default="mac_wrapped_stats.json")
    ap.add_argument("--no-open", action="store_true", help="don't open the video page in your browser")
    args = ap.parse_args()
    print("Counting (nothing is uploaded)...")
    stats = build(args.code)
    Path(args.out).write_text(json.dumps(stats, indent=2))
    found = [k for k in ("mac_apps", "web", "meetings", "code", "terminal", "claude_code", "downloads") if k in stats]
    print(f"Found: {', '.join(found)}. You're {stats['personality']['name']}.")
    for tip in (stats.get("checkup") or {}).get("tips", []):
        print("  tip:", tip)
    print(f"Saved {args.out} (shareable: app names, top websites, projects and commands, counts).")
    if not args.no_open:
        open_studio(stats)


def open_studio(stats):
    """Open the video page with the counts in the URL fragment (after #), which never leaves the browser."""
    packed = base64.urlsafe_b64encode(json.dumps(stats, separators=(",", ":")).encode()).decode().rstrip("=")
    print(f"\nOpening your Mac Wrapped: {STUDIO_URL}")
    if not webbrowser.open(f"{STUDIO_URL}#s={packed}"):
        print("Couldn't open a browser. Open the link above and drop the stats file on it.")


if __name__ == "__main__":
    main()
