#!/usr/bin/env python3
"""Python 3.10+, standard library only. Convert a NARROW teaching archive shape.
Reads data, never executes JavaScript. All occurrences stay in the CSV.
CSV CONTAINS LITERAL UNTRUSTED TEXT: import text columns as Text; do not double-click.
Use a new output directory. Keep originals private and unchanged.
"""
import argparse
from collections import Counter
import csv
import hashlib
import io
import json
from pathlib import Path
import re
import shutil
import sys
import tempfile

MAX_FILE=10*1024*1024
MAX_TOTAL=20*1024*1024
MAX_ROWS=20000
WRAPPER=re.compile(r'\s*window\.YTD\.tweets\.part(0|[1-9][0-9]*)\s*=\s*(\[.*\])\s*;?\s*',re.DOTALL)
COLUMNS=['source_file','record_number','post_id','created_at_source','text','text_state','likes','likes_state']

def unique_keys(pairs):
    result={}
    for k,v in pairs:
        if k in result: raise ValueError('Repeated JSON key')
        result[k]=v
    return result

def reject_constant(value):
    raise ValueError('Non-JSON numeric constant')

def text_field(tweet,key):
    if key not in tweet: return '', 'missing'
    value=tweet[key]
    if value is None: return '', 'null'
    if not isinstance(value,str): raise ValueError(key+' must be a string, null or absent')
    # Excel cannot faithfully retain arbitrary controls or overlong cell text.
    # Keep LF/tab; stop on CR rather than silently normalizing source text.
    if re.search(r'[\x00-\x08\x0b-\x1f\ud800-\udfff\ufffe\uffff]',value) or len(value.encode('utf-16-le'))//2>32767:
        raise ValueError(key+' has unsupported controls or exceeds 32,767 UTF-16 units')
    return value, 'empty' if value=='' else 'present'

def convert(paths):
    if not 1<=len(paths)<=100: raise ValueError('Pass 1 to 100 explicit input files')
    parts={};total=0
    for path in paths:
        with path.open('rb') as f: raw=f.read(MAX_FILE+1)
        total+=len(raw)
        if len(raw)>MAX_FILE or total>MAX_TOTAL: raise ValueError('Limit: 10 MiB/file, 20 MiB total')
        match=WRAPPER.fullmatch(raw.decode('utf-8-sig'))
        if not match: raise ValueError('Unsupported wrapper or extra syntax; inspect original as text')
        part=int(match.group(1))
        if part in parts: raise ValueError('Repeated part number')
        rows=json.loads(match.group(2),object_pairs_hook=unique_keys,parse_constant=reject_constant)
        parts[part]=(path,raw,rows)
    if sorted(parts)!=list(range(len(parts))): raise ValueError('Parts must start at 0 with no gaps')
    output=[];files=[];ids=[];text_states=Counter();likes_states=Counter()
    for part in sorted(parts):
        path,raw,records=parts[part]
        files.append({'name':path.name,'part':part,'sha256':hashlib.sha256(raw).hexdigest(),'records':len(records)})
        for n,record in enumerate(records,1):
            if not isinstance(record,dict) or not isinstance(record.get('tweet'),dict): raise ValueError('Expected nested tweet object')
            tweet=record['tweet'];pid=tweet.get('id_str')
            if not isinstance(pid,str) or not re.fullmatch('[0-9]{1,20}',pid): raise ValueError('id_str must be an exact 1 to 20 digit STRING')
            stamp,stamp_state=text_field(tweet,'created_at')
            if stamp_state!='present': raise ValueError('created_at must be a nonempty string; date parsing is separate')
            text,state=text_field(tweet,'full_text')
            if 'favorite_count' not in tweet: likes='';like_state='missing'
            elif tweet['favorite_count'] is None: likes='';like_state='null'
            else:
                v=tweet['favorite_count']
                if isinstance(v,bool) or not isinstance(v,(int,str)) or not re.fullmatch(r'0|[1-9][0-9]*',str(v)): raise ValueError('favorite_count must be nonnegative integer/string, null or absent')
                if len(str(v))>15: raise ValueError('favorite_count exceeds the 15-digit numeric scope')
                likes=str(v);like_state='value'
            output.append([path.name,str(n),pid,stamp,text,state,likes,like_state]);ids.append(pid)
            text_states[state]+=1;likes_states[like_state]+=1
            if len(output)>MAX_ROWS: raise ValueError('Teaching limit: 20,000 records')
    buffer=io.StringIO(newline='')
    writer=csv.writer(buffer,lineterminator='\r\n',quoting=csv.QUOTE_ALL)
    writer.writerow(COLUMNS);writer.writerows(output)
    csv_bytes=buffer.getvalue().encode('utf-8-sig')
    report={'scope':'Only supplied files; contiguous parts do not prove completeness. Selected fields, not a full backup.',
            'files':files,'source_occurrences':len(output),'distinct_ids':len(set(ids)),
            'repeated_id_occurrences':len(ids)-len(set(ids)), 'text_states':dict(text_states),'likes_states':dict(likes_states),
            'numeric_zero_like_occurrences':sum(r[6]=='0' for r in output),
            'csv_sha256':hashlib.sha256(csv_bytes).hexdigest(),
            'csv_warning':'Literal text, not sanitized for opening. Import with identifier/content columns as Text. Quoting is not formula protection.',
            'timestamp_policy':'Original string retained. No timezone conversion or validity claim.'}
    return csv_bytes,report

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('output',type=Path,help='New, absent output directory')
    parser.add_argument('files',type=Path,nargs='+')
    args=parser.parse_args()
    try:
        if args.output.exists(): raise ValueError('Output directory exists; choose a new name')
        if not args.output.parent.is_dir(): raise ValueError('Output parent directory must exist')
        data,report=convert(args.files)
        # Stage both files; no partial final directory if validation/writing fails.
        with tempfile.TemporaryDirectory(prefix='.csv-stage-',dir=args.output.parent) as tmp:
            stage=Path(tmp)/'result';stage.mkdir()
            (stage/'posts.csv').write_bytes(data)
            (stage/'conversion-note.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
            # mkdir is exclusive: a concurrent run cannot overwrite another result.
            args.output.mkdir()
            try:
                for source in stage.iterdir(): shutil.copyfile(source,args.output/source.name)
            except Exception:
                shutil.rmtree(args.output)
                raise
        print(f'Saved {report["source_occurrences"]} occurrences, {report["distinct_ids"]} IDs. Import posts.csv as Text; do not double-click.')
        return 0
    except (OSError,ValueError,RecursionError) as exc:
        print('Stopped: '+str(exc),file=sys.stderr)
        return 2

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