"""Build static field-review bundles from an explicit list of scan coordinates."""
import argparse
import html
import json
import re
import subprocess
import sys
import tempfile
from datetime import datetime,timezone
from pathlib import Path

from ingest_review import digest,inside


def write_progress(output,jobs,states):
    """Atomically publish a snapshot; it is not a process liveness signal."""
    marker='<!-- generated by diatom_pilot/batch_fields.py -->';links=[]
    labels={'pending':'Pending','checking':'Checking existing output','processing':'Processing','complete':'Complete','failed':'Failed; inspect console and any retained partial output'}
    for job in jobs:
        ident=html.escape(job['id'],quote=True);slide=html.escape(Path(job['slide']).name);status=states[job['id']]
        name=f'<a href="{ident}/">{ident}</a>' if status=='complete' else ident
        links.append(f'<li>{name} · {slide} · field ({job["x"]}, {job["y"]}), Z {job["z"]} · {labels[status]}</li>')
    completed=sum(x=='complete' for x in states.values());timestamp=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
    page=(marker+'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">'
          '<meta http-equiv="refresh" content="30"><title>Field review batch</title>'
          '<style>body{font:16px/1.5 system-ui;color:#1c3835;max-width:70em;margin:2em auto;padding:0 1em}li{margin:.7em 0}</style>'
          f'<h1>Field review batch</h1><p>{completed} of {len(jobs)} fields complete. Snapshot updated {timestamp}.</p>'
          '<p>The page updates at job boundaries. A checking or processing status can be stale if the process stops. '
          'Model proposals and taxon suggestions need human review; these fields are not a validated count.</p><ul>'+''.join(links)+'</ul></html>')
    with tempfile.NamedTemporaryFile('w',dir=output,prefix='.batch-index-',delete=False) as f:
        f.write(page);temporary=Path(f.name)
    temporary.replace(output/'index.html')


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--jobs',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    for key in ('detector','segmenter','encoder','gallery'):p.add_argument('--'+key,type=Path,required=True)
    p.add_argument('--stack-proposals',action='store_true',help='Run detector on all planes and add optional track hypotheses')
    p.add_argument('--tile-proposals',action='store_true',help='Add overlapping tiled detector hypotheses on the model plane')
    p.add_argument('--split-proposals',action='store_true',help='Generate split-mask alternatives for original detector candidates')
    p.add_argument('--species-weights',type=Path,help='Add provisional DIAMORPH predictions for original and stack candidates')
    a=p.parse_args();data=json.loads(a.jobs.read_text());jobs=data.get('fields')
    if data.get('format')!='diatom-field-jobs-v1' or not isinstance(jobs,list) or not jobs:raise ValueError('Invalid field jobs')
    ids=set()
    for job in jobs:
        ident=job.get('id')
        if not isinstance(ident,str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}',ident) or ident in ids:raise ValueError('Invalid or duplicate field ID')
        ids.add(ident)
        if not isinstance(job.get('slide'),str) or not all(type(job.get(k)) is int and job[k]>=0 for k in ('x','y','z')):raise ValueError('Invalid field coordinates or slide')
        size=job.get('size',768)
        if type(size) is not int or not 1<=size<=2048:raise ValueError('Invalid field size')
        if a.tile_proposals and size<384:raise ValueError('Tiled proposals require fields at least 384 pixels wide')
    hashes={key+'_sha256':digest(getattr(a,key)) for key in ('detector','segmenter','encoder')}
    hashes['gallery_manifest_sha256']=digest(a.gallery)
    a.output.mkdir(parents=True,exist_ok=True)
    index=a.output/'index.html';marker='<!-- generated by diatom_pilot/batch_fields.py -->'
    if index.exists() and marker not in index.read_text():raise FileExistsError(f'Refusing to replace unrelated index: {index}')
    states={job['id']:'pending' for job in jobs};write_progress(a.output,jobs,states)
    job=None
    try:
        for job in jobs:
            slide=Path(job['slide']);target=a.output/job['id'];size=job.get('size',768)
            if slide.stat().st_size<1_000_000_000:
                states[job['id']]='failed';write_progress(a.output,jobs,states)
                raise ValueError(f'{slide} is below the 1 GB completed-file cutoff')
            if target.exists():
                states[job['id']]='checking';write_progress(a.output,jobs,states)
                bundle=json.loads((target/'bundle.json').read_text())
                if (bundle.get('slide')!=slide.name or bundle.get('slide_size_bytes')!=slide.stat().st_size
                    or bundle.get('origin_xy')!=[job['x'],job['y']] or bundle.get('z')!=job['z']
                    or bundle.get('size')!=size or bundle.get('models')!=hashes
                    or not (target/'index.html').is_file() or not (target/'focus-planes.json').is_file()):
                    raise ValueError(f'Existing output does not match job: {target}')
                focus=json.loads((target/'focus-planes.json').read_text())
                if focus.get('format')!='diatom-focus-planes-v1' or focus.get('bundle_id')!=bundle['bundle_id']:
                    raise ValueError(f'Invalid existing focus manifest: {target}')
                for plane in focus['planes']:
                    if digest(inside(target,plane['image']))!=plane['sha256']:raise ValueError(f'Existing focus image changed: {target}')
                inside(target,bundle['field_image'])
                for candidate in bundle['candidates']:
                    inside(target,candidate['crop'])
                    if candidate.get('mask'):inside(target,candidate['mask'])
                    for ref in candidate['suggestions']:inside(target,ref['image'])
                if a.stack_proposals and not (target/'stack-proposals.json').is_file():
                    raise ValueError(f'Existing output has no requested stack proposals: {target}; use a new output directory')
                if a.tile_proposals and not (target/'tile-proposals.json').is_file():
                    raise ValueError(f'Existing output has no requested tile proposals: {target}; use a new output directory')
                if a.split_proposals and not (target/'split-alternatives.json').is_file():
                    raise ValueError(f'Existing output has no requested split hypotheses: {target}; use a new output directory')
                if a.species_weights:
                    pred=target/'classifier-suggestions.json'
                    if not pred.is_file() or json.loads(pred.read_text()).get('model_sha256')!=digest(a.species_weights):
                        raise ValueError(f'Existing output has no matching requested species predictions: {target}; use a new output directory')
                    if a.stack_proposals or a.tile_proposals or a.split_proposals:
                        tracks=(json.loads((target/'stack-proposals.json').read_text())['proposals'] if a.stack_proposals else [])
                        tiles=(json.loads((target/'tile-proposals.json').read_text())['proposals'] if a.tile_proposals else [])
                        splits=(json.loads((target/'split-alternatives.json').read_text())['hypotheses'] if a.split_proposals else [])
                        alt=target/'classifier-alternative-suggestions.json'
                        if tracks or tiles or splits:
                            if not alt.is_file():raise ValueError(f'Existing output has no matching alternative predictions: {target}; use a new output directory')
                            predictions=json.loads(alt.read_text())
                            if predictions.get('model_sha256')!=digest(a.species_weights) or not {c['id'] for c in tracks+tiles+splits}<={x['candidate_id'] for x in predictions['records']}:
                                raise ValueError(f'Existing output has no matching alternative predictions: {target}; use a new output directory')
                states[job['id']]='complete';write_progress(a.output,jobs,states)
                print('Already complete:',target,flush=True);continue
            existing=list(a.output.glob('.partial-'+job['id']+'-*'))
            if existing:
                states[job['id']]='failed';write_progress(a.output,jobs,states)
                raise FileExistsError(f'Incomplete prior output requires inspection: {existing[0]}')
            temporary=Path(tempfile.mkdtemp(prefix='.partial-'+job['id']+'-',dir=a.output))
            states[job['id']]='processing';write_progress(a.output,jobs,states)
            command=[sys.executable,str(Path(__file__).with_name('run_field.py')),'--slide',str(slide),
                     '--x',str(job['x']),'--y',str(job['y']),'--z',str(job['z']),'--size',str(size),'--output',str(temporary)]
            for key in ('detector','segmenter','encoder','gallery'):command.extend(['--'+key,str(getattr(a,key))])
            if a.split_proposals:command.append('--split-hypotheses')
            print('Processing',job['id'],slide.name,flush=True)
            try:
                subprocess.run(command,check=True)
                scripts=Path(__file__).parent
                if a.stack_proposals:
                    stack=[sys.executable,str(scripts/'stack_proposals.py'),'--bundle',str(temporary)]
                    for key in ('detector','segmenter','encoder','gallery'):stack.extend(['--'+key,str(getattr(a,key))])
                    subprocess.run(stack,check=True)
                if a.tile_proposals:
                    tiles=[sys.executable,str(scripts/'tile_proposals.py'),'--bundle',str(temporary)]
                    for key in ('detector','segmenter','encoder','gallery'):tiles.extend(['--'+key,str(getattr(a,key))])
                    subprocess.run(tiles,check=True)
                if a.species_weights:
                    classifier=[sys.executable,str(scripts/'classifier_suggestions.py'),'--bundle',str(temporary),'--weights',str(a.species_weights)]
                    subprocess.run(classifier,check=True)
                    if ((a.stack_proposals and json.loads((temporary/'stack-proposals.json').read_text())['proposals'])
                        or (a.tile_proposals and json.loads((temporary/'tile-proposals.json').read_text())['proposals'])
                        or (a.split_proposals and json.loads((temporary/'split-alternatives.json').read_text())['hypotheses'])):
                        subprocess.run(classifier+['--alternatives'],check=True)
            except BaseException:
                states[job['id']]='failed';write_progress(a.output,jobs,states)
                print('Incomplete output retained for inspection:',temporary,flush=True);raise
            temporary.rename(target)
            states[job['id']]='complete';write_progress(a.output,jobs,states)
            print('Complete:',target,flush=True)
    except BaseException:
        if job is not None:
            states[job['id']]='failed'
            try:write_progress(a.output,jobs,states)
            except Exception:pass  # Preserve the original error if the progress page is unwritable.
        raise


if __name__=='__main__':main()
