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

Privacy: this never reads messages, pages or photos. It counts app open/close times, website domains,
call times and lengths, photo dates and kinds, and message timestamps, and it ranks the artists and songs
in your device's now-playing log. Nothing is uploaded. People come out as counts only; the shareable file
has no names, numbers or URLs. 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 --health export.zip # add steps, sleep and workouts from an Apple Health export
    python3 wrapped.py --no-open --out phone_stats.json

What it can see depends on your settings: your iPhone's app use reaches your Mac only when both
are signed into the same Apple Account (Settings > Screen Time > Share Across Devices helps), and
macOS keeps about four weeks of it. Calls, photos and texts cover the full year.
"""
import argparse
import base64
import json
import os
import re
import shutil
import sqlite3
import struct
import subprocess
import tempfile
import webbrowser
import xml.etree.ElementTree as ET
import zipfile
from collections import Counter, defaultdict
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/phone-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
PICKUP_GAP = timedelta(minutes=1)      # back on the phone after a 1+ minute break
LATE = lambda h: h >= 22 or h < 4      # noqa: E731
OFF_HOURS = lambda d: d.weekday() >= 5 or d.hour >= 18 or d.hour < 8   # noqa: E731 - nights and weekends
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)
MIN_PLAYS = 20                         # fewer songs than this isn't a taste
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])")
SOCIAL = {"Instagram", "TikTok", "X", "Twitter", "Reddit", "YouTube", "Snapchat", "Facebook", "Threads", "LinkedIn", "Pinterest", "BeReal"}
CHAT = {"Messages", "WhatsApp", "Telegram", "Signal", "Messenger", "Discord", "Slack", "WeChat"}
DEV = {"Ghostty", "Terminal", "iTerm", "Visual Studio Code", "Cursor", "Xcode", "Zed", "Warp", "Claude"}
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]


# ---------- apps: Biome's App.InFocus stream (this Mac, plus synced iPhone) ----------
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
    """Apple's own lock screens, alarms and overlays show up too; keep Apple bundles only when they're real apps."""
    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 sessions(events):
    """Pair each app's focus-start with its focus-end."""
    opened, out = {}, []
    for t, bundle, started in events:
        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):
                out.append((apple_time(start), t - start, bundle))
    return out


def app_stats(sess):
    if not sess:
        return None
    days = (sess[-1][0].date() - sess[0][0].date()).days + 1
    by_app, opens, by_hour, off_hours = Counter(), Counter(), Counter(), Counter()
    first_of_day, pickups, last_end, hidden, off_total = {}, 0, None, 0, 0
    for start, secs, bundle in sess:
        by_hour[start.hour] += secs
        off_total += secs if OFF_HOURS(start) else 0
        if PRIVATE_APP.search(bundle):
            hidden += secs
        else:
            name = app_name(bundle)
            by_app[name] += secs
            opens[name] += 1
            off_hours[name] += secs if OFF_HOURS(start) else 0
            if start.hour >= 5:
                first_of_day.setdefault(start.date(), name)
        if last_end is None or start - last_end >= PICKUP_GAP:
            pickups += 1
        last_end = start + timedelta(seconds=secs)
    total = sum(by_app.values()) + hidden
    if not by_app:
        return None
    return {
        "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)],
        "most_opened": {"name": opens.most_common(1)[0][0], "per_day": round(opens.most_common(1)[0][1] / days)},
        "pickups_per_day": round(pickups / days),
        "off_hours_per_day": round(off_total / 3600 / days, 1),
        "top_free": [n for n, v in off_hours.most_common(3) if v],
        "first_app": Counter(first_of_day.values()).most_common(1)[0][0] if first_of_day else None,
        "busiest_hour": by_hour.most_common(1)[0][0],
        "late_night_pct": round(100 * sum(v for h, v in by_hour.items() if LATE(h)) / total, 1),
        "apps_used": len(by_app),
    }


def looks_like_phone(events):
    return any(b.startswith(("com.apple.mobilephone", "com.apple.MobileSMS", "com.apple.mobileslideshow")) for _, b, _ in events)


def apps():
    base = HOME / "Library/Biome/streams/restricted/App.InFocus"
    if not base.exists():
        return {}
    out = {"mac": app_stats(sessions(infocus_events(base / "local")))}
    remotes = [infocus_events(d) for d in (base / "remote").glob("*")] if (base / "remote").exists() else []
    phones = [ev for ev in remotes if looks_like_phone(ev)]
    if phones:
        out["phone"] = app_stats(sessions(max(phones, key=len)))
    return {k: v for k, v in out.items() if v}


# ---------- 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():
    """The iPhone's songs when they reach this Mac, otherwise the Mac's own."""
    base = HOME / "Library/Biome/streams/restricted/Media.NowPlaying"
    for folder in (base / "remote", base / "local"):
        found = music_stats(nowplaying_plays(folder)) if folder.exists() else None
        if found:
            return {**found, "device": "iPhone" if folder.name == "remote" else "Mac"}
    return 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))]}


# ---------- calls: the call history your iPhone syncs to your Mac ----------
def calls(now):
    db = HOME / "Library/Application Support/CallHistoryDB/CallHistory.storedata"
    if not db.exists():
        return None, []
    rows = query(db, "SELECT ZDATE, ZDURATION, ZORIGINATED, ZANSWERED, ZSERVICE_PROVIDER, ZADDRESS FROM ZCALLRECORD")
    rows = [(apple_time(d), dur or 0, out, ans, svc or "", addr) for d, dur, out, ans, svc, addr in rows if d and apple_time(d) > now - YEAR]
    if not rows:
        return None, []
    talked = [r for r in rows if r[1] > 0]
    minutes = sum(r[1] for r in talked) / 60
    who = Counter(r[5] for r in talked if r[5])
    missed = sum(1 for r in rows if not r[2] and not r[3])
    span = max((now - min(r[0] for r in rows)).days, 1)
    shared = {
        "days": span, "calls": len(rows), "minutes": round(minutes), "minutes_per_day": round(minutes / span, 1),
        "longest_min": round(max((r[1] for r in rows), default=0) / 60),
        "facetime_pct": round(100 * sum("FaceTime" in r[4] for r in rows) / len(rows), 1),
        "outgoing_pct": round(100 * sum(1 for r in rows if r[2]) / len(rows), 1),
        "missed_pct": round(100 * missed / max(sum(1 for r in rows if not r[2]), 1), 1),
        "busiest_hour": Counter(r[0].hour for r in rows).most_common(1)[0][0],
        "top_caller_share_pct": round(100 * who.most_common(1)[0][1] / max(len(talked), 1), 1) if who else None,
    }
    private = [str(a, "utf-8", "ignore") if isinstance(a, bytes) else a for a, _ in who.most_common(5)]
    return shared, private


# ---------- photos: dates and kinds from the Photos library, never the pictures ----------
def photos(now):
    libs = sorted(HOME.glob("Pictures/*.photoslibrary/database/Photos.sqlite"), key=lambda p: p.stat().st_size, reverse=True)
    if not libs:
        return None
    since = (now - YEAR - APPLE_EPOCH).total_seconds()
    rows = query(libs[0], """
        SELECT z.ZDATECREATED, z.ZKIND, z.ZKINDSUBTYPE, z.ZFAVORITE, z.ZLATITUDE, z.ZLONGITUDE, a.ZCAMERACAPTUREDEVICE
        FROM ZASSET z LEFT JOIN ZADDITIONALASSETATTRIBUTES a ON a.ZASSET = z.Z_PK
        WHERE z.ZTRASHEDSTATE = 0 AND z.ZDATECREATED > ?""", (since,))
    if not rows:
        return None
    days = Counter(apple_time(r[0]).date() for r in rows)
    months = Counter(apple_time(r[0]).strftime("%Y-%m") for r in rows)
    places = {(round(r[4], 1), round(r[5], 1)) for r in rows if r[4] and -90 <= r[4] <= 90 and r[4] != 0}
    best_day, best_count = days.most_common(1)[0]
    return {
        "total": len(rows),
        "photos": sum(1 for r in rows if r[1] == 0 and r[2] != 10),
        "videos": sum(1 for r in rows if r[1] == 1),
        "screenshots": sum(1 for r in rows if r[1] == 0 and r[2] == 10),
        "selfies": sum(1 for r in rows if r[6] == 1),
        "favorites": sum(1 for r in rows if r[3]),
        "per_day": round(len(rows) / 365, 1),
        "busiest_day": best_day.isoformat(), "busiest_day_count": best_count,
        "busiest_month": months.most_common(1)[0][0],
        "places": len(places),   # ~10 km squares with at least one photo
        "days_with_photos": len(days),
        "people": people_in_photos(libs[0]),
    }


def people_in_photos(lib):
    """How many people Photos has recognized in 20 or more shots. A count, never a name."""
    try:
        return query(lib, "SELECT count(*) FROM ZPERSON WHERE ZFACECOUNT >= 20")[0][0]
    except sqlite3.Error:
        return None


# ---------- texts: the headline numbers (the full breakdown is iMessage Wrapped) ----------
def texts(now):
    db = HOME / "Library/Messages/chat.db"
    if not db.exists():
        return None
    since = (now - YEAR - APPLE_EPOCH).total_seconds() * 1e9
    rows = query(db, """
        SELECT m.is_from_me, c.style, c.ROWID FROM message m
        JOIN chat_message_join j ON j.message_id = m.ROWID JOIN chat c ON c.ROWID = j.chat_id
        WHERE m.date > ? AND COALESCE(m.associated_message_type, 0) = 0""", (since,))
    if not rows:
        return None
    one_to_one = Counter(chat for _, style, chat in rows if style != 43)
    return {"total": len(rows), "sent": sum(r[0] for r in rows), "people": len(one_to_one),
            "per_day": round(len(rows) / 365), "group_pct": round(100 * sum(1 for r in rows if r[1] == 43) / len(rows), 1)}


# ---------- health: optional, from the Health app's "Export All Health Data" ----------
ASLEEP = {"HKCategoryValueSleepAnalysisAsleep", "HKCategoryValueSleepAnalysisAsleepCore", "HKCategoryValueSleepAnalysisAsleepDeep",
          "HKCategoryValueSleepAnalysisAsleepREM", "HKCategoryValueSleepAnalysisAsleepUnspecified"}


def health_xml(path):
    p = Path(path).expanduser()
    if p.suffix == ".zip":
        z = zipfile.ZipFile(p)
        name = next(n for n in z.namelist() if n.endswith("/export.xml") or n == "export.xml")
        return z.open(name)
    return open(p, "rb")


def health(path, now):
    """Steps and sleep counted per source, then the larger source per day, so iPhone + Watch aren't double-counted."""
    when = lambda s: datetime.strptime(s, "%Y-%m-%d %H:%M:%S %z")  # noqa: E731
    steps, sleep, workouts = defaultdict(Counter), defaultdict(Counter), Counter()
    since = now - YEAR
    for _, el in ET.iterparse(health_xml(path)):
        tag, a = el.tag, el.attrib
        if tag == "Record" and a.get("type") == "HKQuantityTypeIdentifierStepCount":
            end = when(a["endDate"])
            if end > since:
                steps[end.date()][a.get("sourceName", "")] += float(a["value"])
        elif tag == "Record" and a.get("type") == "HKCategoryTypeIdentifierSleepAnalysis" and a.get("value") in ASLEEP:
            start, end = when(a["startDate"]), when(a["endDate"])
            if end > since:
                sleep[end.date()][a.get("sourceName", "")] += (end - start).total_seconds() / 3600
        elif tag == "Workout" and when(a["endDate"]) > since:
            workouts[a.get("workoutActivityType", "").replace("HKWorkoutActivityType", "")] += 1
        el.clear()
    daily = {d: max(c.values()) for d, c in steps.items()}
    nights = [max(c.values()) for c in sleep.values() if max(c.values()) > 2]
    if not daily and not nights and not workouts:
        return None
    best = max(daily, key=daily.get) if daily else None
    return {
        "steps": round(sum(daily.values())), "steps_per_day": round(sum(daily.values()) / max(len(daily), 1)),
        "best_day": best.isoformat() if best else None, "best_day_steps": round(daily[best]) if best else None,
        "sleep_hours": round(sum(nights) / len(nights), 1) if nights else None,
        "workouts": sum(workouts.values()), "top_workout": workouts.most_common(1)[0][0] if workouts else None,
    }


def find_health_export():
    for p in [HOME / "Downloads/export.zip", HOME / "Downloads/apple_health_export/export.xml"]:
        if p.exists():
            return p
    return None


# ---------- the phone personality: the stat that stands out most ----------
def personality(s):
    phone, mac, web = s.get("phone_apps") or {}, s.get("mac_apps") or {}, s.get("web") or {}
    top_app = (phone.get("top_apps") or [{}])[0]
    share = lambda names, apps: sum(a["share_pct"] for a in apps if a["name"] in names)  # noqa: E731
    chat_share = share(CHAT, phone.get("top_apps", []))
    candidates = [
        ("The Night Owl", (phone.get("late_night_pct") or 0) / 20, f"{phone.get('late_night_pct')}% of my phone time is after 10 pm."),
        ("The Scroller", (top_app.get("share_pct") or 0) / 30 if top_app.get("name") in SOCIAL else 0,
         f"{top_app.get('name')} gets {top_app.get('share_pct')}% of my screen time."),
        ("The Messenger", chat_share / 35, f"{round(chat_share)}% of my phone time is spent talking to people."),
        ("The Shutterbug", ((s.get("photos") or {}).get("per_day") or 0) / 20, f"{(s.get('photos') or {}).get('per_day')} photos a day."),
        ("The Talker", ((s.get("calls") or {}).get("minutes_per_day") or 0) / 30, f"{(s.get('calls') or {}).get('minutes_per_day')} minutes on calls a day."),
        ("The Builder", 1.2 if (mac.get("top_apps") or [{}])[0].get("name") in DEV else 0,
         f"My Mac's top app is {(mac.get('top_apps') or [{}])[0].get('name')}."),
        ("The Researcher", (web.get("pages_per_day") or 0) / 400, f"{web.get('pages_per_day')} web pages a day."),
        ("The Constant Checker", (phone.get("pickups_per_day") or 0) / 120, f"I pick up my phone {phone.get('pickups_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 Balanced One", "why": "No single habit runs my phone."}


# ---------- 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(health_path=None):
    now = datetime.now().astimezone()
    stats = {"made": now.date().isoformat()}
    devices = run("apps", apps) or {}
    stats["phone_apps"], stats["mac_apps"] = devices.get("phone"), devices.get("mac")
    stats["music"] = run("music", music)
    stats["web"] = run("websites", websites, now)
    call_stats = run("calls", calls, now)
    stats["calls"], call_handles = call_stats if call_stats else (None, [])
    stats["photos"] = run("photos", photos, now)
    stats["texts"] = run("texts", texts, now)
    hp = health_path or find_health_export()
    stats["health"] = run("health", health, hp, now) if hp else None
    stats["personality"] = personality(stats)
    return {k: v for k, v in stats.items() if v is not None}, {"top_callers": call_handles}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--health", help="Apple Health export.zip or export.xml (optional)")
    ap.add_argument("--out", default="phone_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, private = build(args.health)
    Path(args.out).write_text(json.dumps(stats, indent=2))
    Path("phone_wrapped_private.json").write_text(json.dumps(private, indent=2))
    found = [k for k in ("phone_apps", "mac_apps", "music", "web", "calls", "photos", "texts", "health") if k in stats]
    print(f"Found: {', '.join(found)}. You're {stats['personality']['name']}.")
    print(f"Saved {args.out} (shareable: app names, top websites, counts) and phone_wrapped_private.json (keep it private).")
    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 Phone 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()
