#!/usr/bin/env python3
"""Portable CLI for the retained Voynich analysis programs. See README.md."""
from pathlib import Path
import argparse, csv, hashlib, html, json, os, re, shutil, sys
from types import SimpleNamespace
BASE=Path(__file__).resolve().parent
sys.path.insert(0,str(BASE/'code'))
sys.dont_write_bytecode=True

def emit(value): print(json.dumps(value,ensure_ascii=False,indent=2,default=float))
def save(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2,default=float)+'\n')
def positive(value):
 n=int(value)
 if n<1: raise argparse.ArgumentTypeError('must be positive')
 return n
def new_output(value,inputs=()):
 p=Path(value).expanduser().absolute()
 if p.exists() or p.is_symlink(): raise ValueError('Output must be a new directory; existing outputs are never overwritten.')
 resolved=p.resolve()
 for q in inputs:
  q=Path(q).resolve()
  if q==resolved or (q.is_dir() and resolved.is_relative_to(q)):
   raise ValueError('Choose an output outside all input directories.')
 p.mkdir(parents=True,exist_ok=False)
 return p

def load_image_config(path,require_images=False):
 path=Path(path);data=json.loads(path.read_text());out={}
 for fol,r in data.items():
  if not re.fullmatch(r'f[0-9]+[rv][0-9]*',fol): raise ValueError('Invalid folio in image configuration')
  p=Path(r['image']);p=p if p.is_absolute() else path.parent/p
  boxes=r['boxes'];scale=float(r['scale'])
  if scale<=0 or not boxes: raise ValueError('Positive scale and nonempty boxes required')
  if require_images:
   from PIL import Image
   with Image.open(p) as im: w,h=im.size
   for box in boxes:
    if len(box)!=4 or not (0<=box[0]<box[2]<=w/scale and 0<=box[1]<box[3]<=h/scale):raise ValueError('Box outside image: '+fol)
  out[fol]=(str(p.resolve()),scale,boxes)
 return out

def configure_measurement(data,transcription,config):
 import item9_seed_crosstab as I, item9_bench_segment as B
 data=Path(data).resolve(); I.ITEM9=str(data/'item9');I.OUT=str(data/'item9b');I.ZL=str(Path(transcription).resolve())
 I.SRC=load_image_config(config); B.SRC=I.SRC
 return I,B

def chunk(a):
 import rag_chunker as C
 paths=[Path(p) for p in a.input]
 if a.max_chars<100:raise ValueError('--max-chars must be at least 100')
 chunks=C.build_chunks(paths=paths,max_chars=a.max_chars)
 if not chunks:raise ValueError('No Markdown/JSON chunks were produced')
 out=new_output(a.output,paths);C.write_chunks(chunks,out/'chunks.jsonl')
 save(out/'run.json',{'operation':'chunk','chunks':len(chunks),'max_chars':a.max_chars,'status_tags':'regex heuristics; never authoritative research status'})
 emit({'output':str(out),'chunks':len(chunks)})

def local_model(name):
 os.environ['HF_HUB_OFFLINE']='1';os.environ['TRANSFORMERS_OFFLINE']='1'
 try:from sentence_transformers import SentenceTransformer
 except ImportError as e:raise ValueError('Local-model mode needs sentence-transformers and a model already cached or supplied locally. No download and no TF-IDF substitution occurred.') from e
 if not name:raise ValueError('--model is required for local-model mode; use a local directory or exact cached model id')
 try:return SentenceTransformer(name,local_files_only=True)
 except Exception as e:raise ValueError('Requested local model could not be loaded offline: '+type(e).__name__) from e

def embed(a):
 import numpy as np, rag_embed as E, rag_chunker as C
 chunks=C.load_chunks(Path(a.chunks))
 if not chunks or len({r['id'] for r in chunks})!=len(chunks):raise ValueError('Nonempty chunks with unique ids required')
 for r in chunks:
  for k in ['source_path','source_section','citation_target','layer_tag','substrate_status_tags']:r['metadata'][k]
 texts=[r['text'] for r in chunks];vocab=idf=None
 if a.backend=='tfidf':
  matrix,vocab,idf=E.build_tfidf_matrix(texts);backend='tfidf-bow';model_name=None
 else:
  model=local_model(a.model);matrix=np.asarray(model.encode(texts,normalize_embeddings=True,show_progress_bar=False),dtype=np.float32);backend='sentence-transformers';model_name=a.model
 if matrix.ndim!=2 or matrix.shape[0]!=len(chunks) or matrix.shape[1]==0:raise ValueError('No usable vector dimensions')
 out=new_output(a.output,[a.chunks]);np.save(out/'embeddings.npy',matrix,allow_pickle=False)
 (out/'chunks.jsonl').write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in chunks))
 payload=E.build_index_payload(chunks,Path('embeddings.npy'),Path('chunks.jsonl'),backend,model_name,['Explicit backend; scores rank retrieved text and do not establish truth.'],vocab,idf)
 payload['vector_shape']=list(matrix.shape);save(out/'index.json',payload)
 emit({'backend':backend,'model_name':model_name,'vector_shape':list(matrix.shape),'output':str(out)})

def query(a):
 import numpy as np,rag_query as Q,rag_chunker as C
 folder=Path(a.index);idx=json.loads((folder/'index.json').read_text())
 # Bundle members are fixed, never executed or loaded with pickle.
 chunks=C.load_chunks(folder/'chunks.jsonl');vectors=np.load(folder/'embeddings.npy',allow_pickle=False,mmap_mode='r')
 if idx['chunk_ids']!=[r['id'] for r in chunks] or vectors.ndim!=2 or vectors.shape[0]!=len(chunks) or list(vectors.shape)!=idx['vector_shape']:raise ValueError('Index/chunk/vector identity mismatch')
 if not a.question.strip():raise ValueError('A nonempty question is required')
 terms=Q.content_terms(a.question)
 if idx['backend']=='tfidf-bow':
  v=Q.build_query_vector_tfidf(terms,idx)
 elif idx['backend']=='sentence-transformers':
  v=np.asarray(local_model(idx['model_name']).encode([a.question],normalize_embeddings=True,show_progress_bar=False)[0],dtype=np.float32)
 else:raise ValueError('Unknown vector backend')
 if v.shape!=(vectors.shape[1],):raise ValueError('Query model/index dimension mismatch')
 scores=vectors@v
 if idx['backend']=='tfidf-bow':scores=Q.rerank_with_overlap(scores,terms,chunks)
 ranks=np.argsort(-scores,kind='stable')[:a.top_k]
 hits=[{'score':float(scores[i]),**chunks[i]} for i in ranks if scores[i]>=a.threshold]
 emit({'backend':idx['backend'],'question':a.question,'threshold':a.threshold,'status':'retrieved' if hits else 'no results above threshold','hits':hits,'interpretation':'Retrieval ranks retained text, including dated and superseded proposals; consult source status.'})

def catalog_build(a):
 import build_file_index as F
 root=Path(a.root).resolve()
 if not root.is_dir():raise ValueError('Catalogue root must be a directory')
 out=new_output(a.output,[root])
 F.build(SimpleNamespace(root=root,output=out,substrate=Path(a.edition) if a.edition else None,move_map=Path(a.move_map) if a.move_map else None,sources=Path(a.sources) if a.sources else None,write_navigation=False))

def catalog_find(a):
 import build_file_index as F
 F.find(SimpleNamespace(output=Path(a.catalog),term=a.term,kind=a.kind,limit=a.limit))

def bench_measure(a):
 I,B=configure_measurement(a.data,a.transcription,a.config)
 data=Path(a.data);required=['pieces_c.csv','pieces_c.npz']
 for name in required:
  if not (data/'item9c'/name).is_file():raise ValueError('Missing retained input: '+name)
 out=new_output(a.output,[data]);B.OUT=str(out)
 for name in required:shutil.copyfile(data/'item9c'/name,out/name)
 B.cmd_measure(SimpleNamespace(perms=a.perms))
 save(out/'RUN_CONTEXT.json',{'operation':'bench-measure','input':'retained masks and geometry','permutations':a.perms,'fixed_seed':I.SEED,'scope':'Three text folios; original leave-one-folio-out controls retain their fixed 2000 permutations. New output is a recomputation, not a promoted reading.'})

def bench_run(a):
 I,B=configure_measurement(a.data,a.transcription,a.config)
 if a.command in ['sheets','segment']:
  I.SRC=load_image_config(a.config,require_images=True);B.SRC=I.SRC
 if a.command=='inventory' and (not a.scan_dir or not Path(a.scan_dir).is_dir()):raise ValueError('inventory needs --scan-dir naming an existing selected directory; only its actual TIFF names are counted')
 data=Path(a.data);out=new_output(a.output,[data]+([a.scan_dir] if a.scan_dir else []));B.OUT=str(out)
 for name in ['pieces_c.csv','pieces_c.npz','label72_sample.csv','label72_raw.txt','label72_labels.csv']:
  shutil.copyfile(data/'item9c'/name,out/name)
 if a.command=='agree':shutil.copytree(data/'item9c/reader2',out/'reader2')
 if a.command=='inventory':
  B.LANE=str(out/'inputs');(out/'inputs/msi/runs/item5').mkdir(parents=True)
  shutil.copyfile(data/'item5/ring3_crops.npz',out/'inputs/msi/runs/item5/ring3_crops.npz');I.TIF=str(Path(a.scan_dir).resolve())
 getattr(B,'cmd_'+a.command)(SimpleNamespace(raw='label72_raw.txt',out='label72_labels.csv',tile=110,cols=6,rows_per_sheet=6,show_max=180,label_n=72))
 save(out/'RUN_CONTEXT.json',{'operation':'bench-'+a.command,'seed':I.SEED,'scope':'Original command in a new output directory. Inventory counts only actual TIFF names in the explicitly selected directory. Reader 2 is the retained blind model read, not an independent human reading.'})

def seed_crosstab(a):
 import numpy as np
 import item9_seed_crosstab as I
 data=Path(a.data);seeds=list(csv.DictReader((data/'item9b/seed_labels.csv').open()))
 records=list(csv.DictReader((data/'item9b/measure_line_counts.csv').open()))
 cols=list(records[0]);start=cols.index('zl_lines')+1;xs=[c for c in cols[start:] if not c.startswith('eva:')];ys=[c for c in cols if c.startswith('eva:')]
 X=np.array([[float(r[c]) for c in xs] for r in records]);Y=np.array([[float(r[c]) for c in ys] for r in records]);groups=[r['folio'] for r in records];units=Y[:,ys.index('eva:units')]
 Xc=np.stack([I.within(X[:,j],groups) for j in range(X.shape[1])],1);Yc=np.stack([I.within(Y[:,j],groups) for j in range(Y.shape[1])],1)
 Xr=np.stack([I.resid(X[:,j],units,groups) for j in range(X.shape[1])],1);Yr=np.stack([I.resid(Y[:,j],units,groups) for j in range(Y.shape[1])],1)
 R=I.corr_cols(Xc,Yc);Rp=I.corr_cols(Xr,Yr);ge=np.zeros_like(R);gep=np.zeros_like(R)
 rng=np.random.default_rng(I.SEED);gi={f:np.where(np.array(groups)==f)[0] for f in sorted(set(groups))}
 for _ in range(a.perms):
  perm=np.arange(len(records))
  for f in sorted(gi):perm[gi[f]]=rng.permutation(gi[f])
  ge+=np.abs(I.corr_cols(Xc[perm],Yc))>=np.abs(R)-1e-12;gep+=np.abs(I.corr_cols(Xr[perm],Yr))>=np.abs(Rp)-1e-12
 out=new_output(a.output,[data])
 for name,M in [('r',R),('partial_r',Rp),('p',(ge+1)/(a.perms+1)),('partial_p',(gep+1)/(a.perms+1))]:
  with (out/('matrix_'+name+'.csv')).open('w',newline='') as f:
   w=csv.writer(f);w.writerow(['shape']+ys)
   for label,row in zip(xs,M):w.writerow([label]+[format(v,'.4f') if np.isfinite(v) else '' for v in row])
 hc=[c for c in I.CLASSES if any(r['hand_class']==c for r in seeds)];rc=sorted({r['rule_class'] for r in seeds})
 I.write_table(str(out/'confusion_rule_vs_hand.csv'),I.table(rc,hc,[(r['rule_class'],r['hand_class']) for r in seeds]),hc)
 save(out/'result.json',{'seed_labels':len(seeds),'lines':len(records),'shape_variables':xs,'eva_variables':ys,'rule_agreement':sum(r['rule_class']==r['hand_class'] for r in seeds)/len(seeds),'seed':I.SEED,'permutations':a.perms,'scope':'Recomputes crosstab from retained propagated line counts. Does not rerun nearest-neighbour propagation or replace its historical control results. Permutation stream starts fresh; compare r and partial_r exactly, not historic p.'})
 emit({'output':str(out),'lines':len(records),'seed_labels':len(seeds)})

def seed_run(a):
 I,B=configure_measurement(a.data,a.transcription,a.config)
 if a.command in ['sample','lines','measure']:I.SRC=load_image_config(a.config,require_images=True)
 data=Path(a.data);out=new_output(a.output,[data]);I.OUT=str(out)
 if a.command!='sample':
  for name in ['seed_labels.csv','seed_sample.csv','pieces_geom.csv']:
   shutil.copyfile(data/'item9b'/name,out/name)
  if (data/'item9b/labels_raw').exists():shutil.copytree(data/'item9b/labels_raw',out/'labels_raw')
 getattr(I,'cmd_'+a.command)(SimpleNamespace(perms=a.perms,control=150,tile=110,cols=6,rows_per_sheet=6))
 save(out/'RUN_CONTEXT.json',{'operation':'seed-'+a.command,'seed':I.SEED,'permutations':a.perms,'scope':'Original configured command in a new output directory. Exact historical segmentation requires original-resolution scans matching retained clusters.'})

def segment(a):
 import numpy as np
 import item9_seed_crosstab as I,item9_bench_segment as B
 config=load_image_config(a.config,require_images=True);I.SRC=config;B.SRC=config
 dmaps={};pieces=B.segment_comp(dmaps=dmaps)
 if not pieces:raise ValueError('No ink components found in configured regions')
 merged,groups=B.merge_pieces(pieces,dmaps=dmaps)
 out=new_output(a.output,[a.config]+[v[0] for v in config.values()])
 np.savez_compressed(out/'masks.npz',**{'p'+str(i):p['mask'] for i,p in enumerate(merged)})
 fields=['pid','source','box','x','y','w','h','med_h','kind','n_parts','parts','holes','bar_frac','bar_row']
 with (out/'pieces.csv').open('w',newline='') as f:
  w=csv.DictWriter(f,fields);w.writeheader()
  for i,p in enumerate(merged):w.writerow({k:(i if k=='pid' else p['src'] if k=='source' else p.get(k)) for k in fields})
 save(out/'result.json',{'original_pieces':len(pieces),'merged_pieces':len(merged),'params':B.PARAMS,'source_sha256':{k:hashlib.sha256(Path(v[0]).read_bytes()).hexdigest() for k,v in config.items()},'scope':'Geometric proposals on selected image regions. Scale or image changes can change component counts; no automatic glyph identity or semantic binding.'})
 emit({'output':str(out),'original_pieces':len(pieces),'merged_pieces':len(merged)})

def atlas(a):
 import build_atlas as A
 image=Path(a.image)
 if not image.is_file():raise ValueError('Supply --image; standalone download also contains data/f1r.jpg')
 if not re.fullmatch(r'f[0-9]+[rv][0-9]*',a.folio):raise ValueError('Invalid folio')
 A.TRANS=Path(a.transcription);trans=A.parse_transcription([a.folio])[a.folio]
 if not trans:raise ValueError('No lines for folio in transcription')
 bands,size=A.detect_lines(image)
 out=new_output(a.output,[image,a.transcription]);(out/'crops').mkdir();shutil.copyfile(image,out/('source'+image.suffix.lower()))
 mappings={int(k):int(v) for k,v in json.loads(Path(a.line_map).read_text()).items()} if a.line_map else {}
 known={n for n,t in trans}
 if any(k<1 or k>len(bands) or v not in known for k,v in mappings.items()):raise ValueError('Line-map keys must be detected band numbers; values must exist in transcription')
 bandrows=[]
 for i,(y0,y1) in enumerate(bands,1):
  A.crop_line(image,y0,y1).save(out/f'crops/band-{i:03}.png')
  bandrows.append({'band':i,'y0':y0,'y1':y1,'crop':f'crops/band-{i:03}.png','transcription_line':mappings.get(i),'alignment':'user supplied' if i in mappings else 'unassigned'})
 units={u:[] for u in A.EVA_UNITS};records=[]
 for n,t in trans:
  wordrows=[]
  for wi,word in enumerate(t.split(),1):
   toks=A.tokenize_eva(word);wordrows.append({'word':wi,'text':word,'units':toks})
   for u in set(toks):units[u].append({'line':n,'word':wi,'text':word})
  records.append({'line':n,'eva':t,'words':wordrows})
 result={'folio':a.folio,'image_size':size,'bands':bandrows,'transcription':records,'units':units,'scope':'Image bands and transcription are separate observations. Only explicit user mappings join them. Longest-match EVA units are transcription segments, not asserted glyph bounding boxes.'};save(out/'atlas.json',result)
 esc=html.escape;title=esc(a.folio+' — EVA line atlas')
 page=['<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>'+title+'</title><style>body{max-width:1100px;margin:2rem auto;padding:1rem;font:18px/1.6 system-ui}img{max-width:100%}section{margin-block:3rem}td,th{padding:.4rem;text-align:left}a{color:#286087}</style><h1>'+title+'</h1><p>'+esc(result['scope'])+'</p><a href="atlas.json">Complete structured data</a><h2>Transcription</h2>']
 for r in records:page.append('<p id="line-'+str(r['line'])+'"><strong>'+str(r['line'])+'</strong> '+esc(r['eva'])+'</p>')
 page.append('<h2>Detected image bands</h2>')
 for r in bandrows:page.append('<section><h3>Band '+str(r['band'])+' · '+esc(str(r['alignment']))+'</h3><p>Image y '+str(r['y0'])+'–'+str(r['y1'])+('; transcription line '+str(r['transcription_line']) if r['transcription_line'] else '')+'</p><img alt="Detected manuscript band '+str(r['band'])+'" src="'+r['crop']+'"></section>')
 page.append('<h2>EVA unit contexts</h2>')
 for u,items in units.items():page.append('<section id="unit-'+u+'"><h3>'+u+'</h3>'+''.join('<a href="#line-'+str(r['line'])+'">line '+str(r['line'])+', word '+str(r['word'])+': '+esc(r['text'])+'</a><br>' for r in items)+'</section>')
 page.append('</html>');(out/'index.html').write_text('\n'.join(page));emit({'output':str(out),'image_bands':len(bands),'transcription_lines':len(trans)})

def main():
 p=argparse.ArgumentParser(description=__doc__);s=p.add_subparsers(dest='operation',required=True)
 q=s.add_parser('chunk',help='Original Markdown/JSON chunking');q.add_argument('--input',nargs='+',required=True);q.add_argument('--max-chars',type=positive,default=2000)
 q=s.add_parser('embed',help='Build explicit TF-IDF or cached-model vectors');q.add_argument('--chunks',required=True);q.add_argument('--backend',choices=['tfidf','local-model'],required=True);q.add_argument('--model')
 q=s.add_parser('query',help='Read-only retrieval with original overlap reranking');q.add_argument('--index',required=True);q.add_argument('--question',required=True);q.add_argument('--top-k',type=positive,default=5);q.add_argument('--threshold',type=float,default=.3)
 q=s.add_parser('catalog-build',help='Metadata catalogue; never updates source navigation');q.add_argument('--root',required=True);q.add_argument('--edition',default=str(BASE/'data/catalog-records.json'));q.add_argument('--move-map');q.add_argument('--sources')
 q=s.add_parser('catalog-find',help='Read-only metadata search');q.add_argument('--catalog',required=True);q.add_argument('--term',required=True);q.add_argument('--limit',type=positive,default=20);q.add_argument('--kind',choices=['all','file','finding','manuscript','citation','route'],default='all')
 for name in ['bench-measure','seed-crosstab','seed-run','bench-run']:
  q=s.add_parser(name);q.add_argument('--data',default=str(BASE/'data/hartlieb'));q.add_argument('--perms',type=positive,default=10000);q.add_argument('--transcription',default=str(BASE/'data/transcription.ivtff'));q.add_argument('--config',default=str(BASE/'data/historical-image-config.json'))
  if name=='seed-run':q.add_argument('--command',choices=['sample','assemble','lines','measure'],required=True)
  if name=='bench-run':
   q.add_argument('--command',choices=['labels','agree','inventory','sheets','segment'],required=True);q.add_argument('--scan-dir')
 q=s.add_parser('segment',help='Connected components and bench-preserving merging on selected images');q.add_argument('--config',required=True)
 q=s.add_parser('atlas',help='Local source image bands, full transcription and EVA unit contexts');q.add_argument('--image',default=str(BASE/'data/f1r.jpg'));q.add_argument('--folio',default='f1r');q.add_argument('--transcription',default=str(BASE/'data/transcription.ivtff'));q.add_argument('--line-map',help='JSON object from image band number to transcription line, explicitly supplied')
 for name,q in s.choices.items():
  if name not in ['query','catalog-find']:q.add_argument('--output',required=True,help='New directory, outside input directories; never overwritten')
 a=p.parse_args()
 try:globals()[a.operation.replace('-','_')](a)
 except (ValueError,FileNotFoundError,KeyError,ImportError) as e:p.exit(2,'Input/prerequisite error: '+str(e)+'\n')
if __name__=='__main__':main()
