"""Multipra AI log aggregator. Runs on YOUR computer; the raw log never leaves it.
Usage:  python3 multipra_ai_log_aggregator.py signins.csv [more files...] [--candidates] > multipra_upload.json
Reads Entra ID / Google Workspace sign-in exports (CSV or JSON) or proxy/DNS logs (CSV or text).
Outputs only, per AI service domain or app: number of distinct users, number of events, first and last seen.
No user names, no other websites, no message content. Upload the output file in the Multipra portal."""
import csv, io, json, re, sys
SERVICES = [{"domains": ["character.ai", "beta.character.ai"], "apps": ["Character.AI"]}, {"domains": ["chatgpt.com", "chat.openai.com", "api.openai.com", "openai.com"], "apps": ["ChatGPT", "OpenAI"]}, {"domains": ["claude.ai", "api.anthropic.com", "anthropic.com"], "apps": ["Claude", "Anthropic"]}, {"domains": ["cohere.com", "api.cohere.com", "cohere.ai"], "apps": ["Cohere"]}, {"domains": ["cursor.com", "cursor.sh", "api2.cursor.sh"], "apps": ["Cursor"]}, {"domains": ["deepl.com", "api.deepl.com"], "apps": ["DeepL"]}, {"domains": ["chat.deepseek.com", "api.deepseek.com", "deepseek.com"], "apps": ["DeepSeek"]}, {"domains": ["elevenlabs.io"], "apps": ["ElevenLabs"]}, {"domains": ["fireflies.ai", "app.fireflies.ai"], "apps": ["Fireflies"]}, {"domains": ["gamma.app"], "apps": ["Gamma"]}, {"domains": ["gemini.google.com", "aistudio.google.com", "generativelanguage.googleapis.com", "bard.google.com"], "apps": ["Gemini", "Google AI Studio"]}, {"domains": ["copilot-proxy.githubusercontent.com", "api.githubcopilot.com"], "apps": ["GitHub Copilot"]}, {"domains": ["grammarly.com", "grammarly.io"], "apps": ["Grammarly"]}, {"domains": ["grok.com", "x.ai", "api.x.ai"], "apps": ["Grok"]}, {"domains": ["groq.com", "api.groq.com"], "apps": ["Groq"]}, {"domains": ["huggingface.co", "hf.co"], "apps": ["Hugging Face"]}, {"domains": ["jasper.ai", "app.jasper.ai"], "apps": ["Jasper"]}, {"domains": ["chat.mistral.ai", "api.mistral.ai"], "apps": ["Mistral", "Le Chat"]}, {"domains": ["copilot.microsoft.com", "copilot.cloud.microsoft"], "apps": ["Microsoft Copilot", "Copilot"]}, {"domains": ["midjourney.com"], "apps": ["Midjourney"]}, {"domains": ["otter.ai"], "apps": ["Otter.ai", "Otter"]}, {"domains": ["perplexity.ai", "www.perplexity.ai"], "apps": ["Perplexity"]}, {"domains": ["poe.com"], "apps": ["Poe"]}, {"domains": ["replit.com"], "apps": ["Replit"]}, {"domains": ["runwayml.com", "app.runwayml.com"], "apps": ["Runway"]}, {"domains": ["synthesia.io"], "apps": ["Synthesia"]}, {"domains": ["together.ai", "api.together.xyz"], "apps": ["Together AI"]}, {"domains": ["writebot.ai"], "apps": []}]
CANDIDATES = '--candidates' in sys.argv  # opt-in: also report unknown domains that look like AI services (counts only)
AI_LIKE = re.compile(r'(^|[.-])(gpt|llm|copilot|chat|assistant|genai)([.-]|$)|\.ai$', re.I)
HOST_RE = re.compile(r'(?:https?://)?((?:[a-z0-9-]+\.)+[a-z]{2,24})', re.I)
TS_RE = re.compile(r'\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?')
def svc(app, host):
    for i, s in enumerate(SERVICES):
        if host and any(host == d or host.endswith('.' + d) for d in s['domains']): return 'host', next(d for d in s['domains'] if host == d or host.endswith('.' + d))
        if app and any(a.lower() == app.lower() or (len(a) > 4 and a.lower() in app.lower()) for a in s['apps']): return 'app', app
    return None, None
def rows(text):
    t = text.lstrip()
    if t[:1] in '[{':
        try:
            d = json.loads(t); d = d.get('value', d) if isinstance(d, dict) else d
        except ValueError:
            d = [json.loads(l) for l in t.splitlines() if l.strip().startswith('{')]
        for r in d:
            if isinstance(r, dict): yield {str(k).lower(): v for k, v in r.items()}
    elif t and ',' in t.splitlines()[0]:
        for r in csv.DictReader(io.StringIO(t)): yield {str(k).strip().lower(): v for k, v in r.items()}
    else:
        for line in t.splitlines(): yield {'_line': line}
pick = lambda r, ks: next((str(r[k]) for k in ks if r.get(k) not in (None, '')), '')
agg = {}
for path in [x for x in sys.argv[1:] if not x.startswith('--')]:
    for r in rows(open(path, encoding='utf-8-sig', errors='replace').read()):
        line = r.get('_line')
        if line is not None:
            hs = HOST_RE.findall(line); host = hs[0].lower() if hs else ''; app = ''
            u = re.search(r'[\w.+-]+@[\w-]+\.[\w.]+|\b\d{1,3}(?:\.\d{1,3}){3}\b', line); user = u.group(0) if u else ''; m = TS_RE.search(line); when = m.group(0) if m else ''
        else:
            h = HOST_RE.search(pick(r, ('domain', 'host', 'hostname', 'query', 'qname', 'url', 'destination', 'dest_host', 'site', 'fqdn', 'sni'))); host = h.group(1).lower() if h else ''
            app = pick(r, ('application', 'appdisplayname', 'application name', 'app', 'app name', 'client id', 'application id', 'appid'))
            user = pick(r, ('userprincipalname', 'username', 'user', 'email', 'actor', 'user email', 'src_user', 'client', 'source ip', 'src', 'client ip', 'ip'))
            m = TS_RE.search(pick(r, ('date (utc)', 'createddatetime', 'timestamp', 'time', 'date', 'datetime', 'event time', '@timestamp'))); when = m.group(0) if m else ''
        kind, key = svc(app, host)
        if not kind and CANDIDATES and host and AI_LIKE.search(host): kind, key = 'candidate', host
        if not kind: continue
        e = agg.setdefault((kind, key), {'users': set(), 'events': 0, 'first': '', 'last': ''})
        e['events'] += 1
        if user: e['users'].add(user.lower())
        if when:
            e['first'] = min(e['first'] or when, when); e['last'] = max(e['last'], when)
out = {'multipra_aggregate': 1, 'items': [dict({('host' if k in ('host', 'candidate') else 'app'): v}, **({'candidate': 1} if k == 'candidate' else {}), **{ 'users': len(e['users']), 'events': e['events'], 'first': e['first'], 'last': e['last']}) for (k, v), e in sorted(agg.items())]}
print(json.dumps(out, indent=1))
