#!/usr/bin/env python3
"""AI Wrapped: your year with coding agents, counted on your machine.

Reads the session history Claude Code and Codex keep on disk, and Amp's thread list through the amp CLI, adds it up,
and opens the wrapped page with the totals in the link's fragment. A browser never sends a fragment to a server, and
the totals hold no prompt, path, project or thread name. `--json` prints exactly what the link carries.
"""
import argparse
import base64
import json
import os
import re
import shutil
import subprocess
import sys
import webbrowser
import zlib
from collections import Counter, defaultdict
from datetime import date, datetime, timedelta
from pathlib import Path

SITE = 'https://altitudemcp.com'
VERSION = 1
# A gap longer than this between two events of a session is time away, not time working.
IDLE = timedelta(minutes=30)
NOISE = re.compile(r'<(system-reminder|local-command-\w+|command-\w+|task-notification)\b.*?</\1>', re.S)
INTERRUPT = '[Request interrupted by user'
DATED = re.compile(r'-\d{8}$')


def moment(text):
    if not text:
        return None
    try:
        return datetime.fromisoformat(str(text).replace('Z', '+00:00')).astimezone()
    except ValueError:
        return None


def tool(name):
    return 'mcp' if name.startswith('mcp__') else name


def model(name):
    return DATED.sub('', name)


class Tally:
    """Everything counted, across sources. A session is one Claude Code session file, one Codex rollout or one Amp
    thread; its days and hours are the ones it was active in."""

    def __init__(self, year):
        self.year = year
        self.sources = {}
        self.days = Counter()
        self.slots = set()
        self.models = Counter()
        self.tools = Counter()
        self.projects = set()
        self.tokens = {'in': 0, 'out': 0}
        self.prompts = self.words = self.calls = self.sessions = 0
        self.minutes = 0.0
        self.longest = None

    def within(self, when):
        return when is not None and when.year == self.year

    def source(self, name):
        return self.sources.setdefault(name, Counter())

    def session(self, source, key, moments, prompts, project=None):
        """One session's moments, already limited to the year. Adds its days, its hours and its working time."""
        moments = sorted(moments)
        if not moments:
            return
        self.sessions += 1
        self.source(source)['s'] += 1
        if project:
            self.projects.add(project)
        for when in moments:
            self.slots.add((source, key, when.date(), when.hour))
        for day in {when.date() for when in moments}:
            self.days[day] += 1
        worked = sum((later - earlier for earlier, later in zip(moments, moments[1:]) if later - earlier <= IDLE), timedelta())
        minutes = worked.total_seconds() / 60
        self.minutes += minutes
        if self.longest is None or minutes > self.longest['min']:
            self.longest = {'min': round(minutes), 'p': prompts, 'd': moments[0].date().isoformat(), 'src': source}

    def prompt(self, source, text):
        self.prompts += 1
        self.words += len(text.split())
        self.source(source)['p'] += 1

    def summary(self, name=None):
        hours, weekdays = [0] * 24, [0] * 7
        for _, _, day, hour in self.slots:
            hours[hour] += 1
            weekdays[day.weekday()] += 1
        start = date(self.year, 1, 1)
        length = (date(self.year + 1, 1, 1) - start).days
        days = [self.days.get(start + timedelta(days=offset), 0) for offset in range(length)]
        active = [day for day in sorted(self.days)]
        streak = best = 0
        previous = None
        for day in active:
            streak = streak + 1 if previous and day - previous == timedelta(days=1) else 1
            best = max(best, streak)
            previous = day
        busiest = max(active, key=lambda day: (self.days[day], day)) if active else None
        return {
            'v': VERSION,
            'y': self.year,
            'name': name,
            'src': {key: dict(counts) for key, counts in sorted(self.sources.items()) if counts.get('s')},
            's': self.sessions,
            'p': self.prompts,
            'w': self.words,
            'tk': self.tokens,
            'calls': self.calls,
            'min': round(self.minutes),
            'pj': len(self.projects),
            'd': days,
            'h': hours,
            'wd': weekdays,
            'active': len(active),
            'streak': best,
            'first': active[0].isoformat() if active else None,
            'busiest': {'d': busiest.isoformat(), 's': self.days[busiest]} if busiest else None,
            'm': [[name, count] for name, count in self.models.most_common(5)],
            'tl': [[name, count] for name, count in self.tools.most_common(6)],
            'long': self.longest,
        }


def text_of(content):
    if isinstance(content, str):
        return content
    return ' '.join(part.get('text', '') for part in content or [] if isinstance(part, dict) and part.get('type') == 'text')


def claude_roots():
    configured = os.environ.get('CLAUDE_CONFIG_DIR')
    roots = [Path(folder) for folder in configured.split(',')] if configured else []
    roots += [Path.home() / '.claude', Path.home() / '.config' / 'claude']
    seen = []
    for root in roots:
        projects = (root / 'projects').expanduser()
        if projects.is_dir() and projects.resolve() not in [folder.resolve() for folder in seen]:
            seen.append(projects)
    return seen


def claude(tally, folders):
    """Claude Code keeps a session per file under projects/<folder>/. A subagent's file sits under its session's own
    folder: its tokens and tool calls count, its prompts are the parent's. One reply is spread over several lines
    that repeat its usage, so usage counts once per message id."""
    for folder in folders:
        for path in folder.rglob('*.jsonl'):
            subagent = 'subagents' in path.parts
            moments, prompts, cwd, seen = [], 0, None, set()
            try:
                lines = open(path, errors='replace')
            except OSError:
                continue
            with lines:
                for line in lines:
                    if '"timestamp"' not in line:
                        continue
                    try:
                        entry = json.loads(line)
                    except ValueError:
                        continue
                    when = moment(entry.get('timestamp'))
                    if not tally.within(when):
                        continue
                    kind = entry.get('type')
                    message = entry.get('message') or {}
                    if kind == 'assistant':
                        moments.append(when)
                        key = message.get('id') or entry.get('uuid')
                        name = message.get('model') or ''
                        if key not in seen:
                            seen.add(key)
                            usage = message.get('usage') or {}
                            tally.tokens['in'] += sum(usage.get(field) or 0 for field in ('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'))
                            tally.tokens['out'] += usage.get('output_tokens') or 0
                            tally.source('claude')['t'] += sum(usage.get(field) or 0 for field in ('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens', 'output_tokens'))
                            if name and not name.startswith('<'):
                                tally.models[model(name)] += 1
                        for part in message.get('content') or []:
                            if isinstance(part, dict) and part.get('type') == 'tool_use':
                                tally.calls += 1
                                tally.tools[tool(part.get('name') or '')] += 1
                    elif kind == 'user' and not subagent and not entry.get('isMeta') and not entry.get('isSidechain'):
                        content = message.get('content')
                        cwd = cwd or entry.get('cwd')
                        if isinstance(content, list) and any(isinstance(part, dict) and part.get('type') == 'tool_result' for part in content):
                            moments.append(when)
                            continue
                        text = NOISE.sub('', text_of(content)).strip()
                        if text and not text.startswith(INTERRUPT) and not text.startswith('<'):
                            moments.append(when)
                            prompts += 1
                            tally.prompt('claude', text)
            if not subagent:
                tally.session('claude', str(path), moments, prompts, cwd)


def codex_folders():
    home = Path(os.environ.get('CODEX_HOME') or Path.home() / '.codex').expanduser()
    return [folder for folder in (home / 'sessions', home / 'archived_sessions') if folder.is_dir()]


def codex(tally, folders):
    """Codex writes a rollout per session. Its token counts are running totals, so the session's last one is its
    total."""
    for folder in folders:
        for path in folder.rglob('rollout-*.jsonl'):
            moments, prompts, cwd, total = [], 0, None, None
            try:
                lines = open(path, errors='replace')
            except OSError:
                continue
            with lines:
                for line in lines:
                    try:
                        entry = json.loads(line)
                    except ValueError:
                        continue
                    when = moment(entry.get('timestamp'))
                    if not tally.within(when):
                        continue
                    moments.append(when)
                    kind, payload = entry.get('type'), entry.get('payload') or {}
                    inner = payload.get('type')
                    if kind in ('session_meta', 'turn_context'):
                        cwd = cwd or payload.get('cwd')
                        if kind == 'turn_context' and payload.get('model'):
                            tally.models[model(payload['model'])] += 1
                    elif kind == 'event_msg' and inner == 'user_message':
                        text = (payload.get('message') or '').strip()
                        if text:
                            prompts += 1
                            tally.prompt('codex', text)
                    elif kind == 'event_msg' and inner == 'token_count':
                        total = ((payload.get('info') or {}).get('total_token_usage')) or total
                    elif kind == 'response_item' and inner in ('function_call', 'custom_tool_call', 'local_shell_call'):
                        tally.calls += 1
                        tally.tools[tool(payload.get('name') or 'shell')] += 1
            if total:
                tally.tokens['in'] += total.get('input_tokens') or 0
                tally.tokens['out'] += total.get('output_tokens') or 0
                tally.source('codex')['t'] += (total.get('input_tokens') or 0) + (total.get('output_tokens') or 0)
            tally.session('codex', str(path), moments, prompts, cwd)


def amp_threads(binary):
    """Every thread of the signed-in Amp account, archived ones included, 500 a page. None when amp can't answer."""
    threads = []
    while True:
        try:
            done = subprocess.run([binary, 'threads', 'list', '--json', '--include-archived', '--limit', '500', '--offset', str(len(threads))],
                                  capture_output=True, text=True, timeout=120)
            page = json.loads(done.stdout) if done.returncode == 0 else None
        except (OSError, subprocess.TimeoutExpired, ValueError):
            page = None
        if page is None:
            return threads or None
        threads += page
        if len(page) < 500:
            return threads


def amp(tally, threads):
    """Amp keeps threads on its server, and its list gives each one's last change and message count, not its prompts
    or tokens. A thread counts as a session on the day and hour it last changed."""
    for thread in threads:
        when = moment(thread.get('updated'))
        if not tally.within(when):
            continue
        tally.source('amp')['m'] += thread.get('messageCount') or 0
        tally.session('amp', thread.get('id') or '', [when], 0, (thread.get('tree') or '').removeprefix('file://') or None)


def link(site, summary):
    packed = zlib.compress(json.dumps(summary, separators=(',', ':')).encode(), 9)
    return f"{site.rstrip('/')}/wrapped#v{VERSION}.{base64.urlsafe_b64encode(packed).decode().rstrip('=')}"


def main(argv=None):
    parser = argparse.ArgumentParser(description='Count your year with coding agents on this machine, and open it as a wrapped story.')
    parser.add_argument('--year', type=int, default=date.today().year)
    parser.add_argument('--name', help='A name for the share card, such as your handle.')
    parser.add_argument('--json', action='store_true', help='Print exactly what the link carries, and open nothing.')
    parser.add_argument('--print', dest='quiet', action='store_true', help='Print the link and open no browser.')
    parser.add_argument('--no-amp', action='store_true', help="Leave Amp's threads out.")
    parser.add_argument('--claude', action='append', help='A Claude Code projects folder to read instead of the usual ones.')
    parser.add_argument('--codex', action='append', help='A Codex sessions folder to read instead of the usual ones.')
    parser.add_argument('--amp', default=shutil.which('amp'), help=argparse.SUPPRESS)
    parser.add_argument('--site', default=SITE, help=argparse.SUPPRESS)
    args = parser.parse_args(argv)

    tally = Tally(args.year)
    read = []
    claude_folders = [Path(folder).expanduser() for folder in args.claude] if args.claude else claude_roots()
    if claude_folders:
        claude(tally, claude_folders)
        read.append(f"Claude Code: {tally.sources.get('claude', {}).get('s', 0)} sessions")
    codex_paths = [Path(folder).expanduser() for folder in args.codex] if args.codex else codex_folders()
    if codex_paths:
        codex(tally, codex_paths)
        read.append(f"Codex: {tally.sources.get('codex', {}).get('s', 0)} sessions")
    if not args.no_amp and args.amp:
        threads = amp_threads(args.amp)
        if threads is not None:
            amp(tally, threads)
            read.append(f"Amp: {tally.sources.get('amp', {}).get('s', 0)} threads")

    summary = tally.summary(args.name)
    if args.json:
        print(json.dumps(summary, indent=2))
        return 0
    if not tally.sessions:
        print(f"No agent sessions from {args.year} on this machine. Read: {', '.join(read) or 'nothing; no Claude Code, Codex or Amp history found'}.", file=sys.stderr)
        return 1

    url = link(args.site, summary)
    print(f"Read {', '.join(read)}.")
    print('The link carries totals only: no prompt, path, project or thread name. See them with --json.')
    print(url)
    if not args.quiet:
        webbrowser.open(url)
    return 0


if __name__ == '__main__':
    sys.exit(main())
