#!/usr/bin/env python3
"""Extract claimed crawler identities from standard Nginx combined logs.
No network calls; does not authenticate agents. Paths may contain private data.
Keep the output local and review it before sharing.
"""
import csv
import re
import sys
from datetime import datetime

AGENTS = ('OAI-SearchBot', 'GPTBot', 'ChatGPT-User', 'Claude-SearchBot',
          'ClaudeBot', 'Claude-User', 'PerplexityBot', 'Perplexity-User', 'Googlebot')
PATTERNS = [(a, re.compile(r'(?<![\w-])' + re.escape(a) + r'(?![\w-])', re.I)) for a in AGENTS]
QUOTED = r'"((?:[^"\\]|\\.)*)"'
COMBINED = re.compile(r'^\S+ \S+ \S+ \[([^\]]+)\] ' + QUOTED + r' (\d{3}) (?:\d+|-) ' + QUOTED + ' ' + QUOTED + r'\s*$')


def parse(line):
    m = COMBINED.fullmatch(line.rstrip('\r\n'))
    if not m:
        return 'malformed', None
    timestamp, request, status, _, ua = m.groups()
    names = [name for name, pattern in PATTERNS if pattern.search(ua)]
    if not names:
        return 'other', None
    if len(names) != 1:
        return 'ambiguous', None
    parts = request.split()
    if len(parts) != 3 or not parts[2].startswith('HTTP/'):
        return 'malformed', None
    target = parts[1]
    if not target.startswith('/') or '#' in target or any(ord(c) < 32 or ord(c) == 127 for c in target):
        return 'malformed', None
    path = target.split('?', 1)[0]
    # Preserve double slashes; urlsplit would interpret them as an authority.
    try:
        datetime.strptime(timestamp, '%d/%b/%Y:%H:%M:%S %z')
    except ValueError:
        return 'malformed', None
    if not 100 <= int(status) <= 599:
        return 'malformed', None
    method = parts[0]
    if not re.fullmatch(r'[A-Z]+', method):
        return 'malformed', None
    return 'candidate', (timestamp, method, path, status, names[0], 'unverified')


def main():
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 crawler-candidates.py access.log > candidates.csv')
    writer = csv.writer(sys.stdout)
    writer.writerow(['line_number', 'timestamp_as_logged', 'method', 'path', 'status', 'claimed_agent', 'identity_state'])
    counts = dict.fromkeys(('candidate', 'other', 'malformed', 'ambiguous'), 0)
    with open(sys.argv[1], encoding='utf-8', errors='replace') as source:
        for number, line in enumerate(source, 1):
            kind, row = parse(line)
            counts[kind] += 1
            if row:
                writer.writerow((number, *row))
    print(' '.join(f'{k}={v}' for k, v in counts.items()), file=sys.stderr)


if __name__ == '__main__':
    main()
