#!/usr/bin/env python3
"""Fail-closed STEP4 artifact gate. Structural evidence checks, not semantic certification."""
import argparse,csv,datetime,hashlib,json,re,sys
from pathlib import Path
from html.parser import HTMLParser

DIMENSIONS={'D1':'diagnose','D2':'choose','D3':'perform','D4':'prevent','D5':'verify','D6':'remedy'}
class TextHTML(HTMLParser):
 def __init__(self): super().__init__(convert_charrefs=True);self.text=[];self.anchors={};self.stack=[]
 def handle_starttag(self,tag,attrs):
  d=dict(attrs);self.stack.append((tag,d.get('id')))
  if d.get('id'): self.anchors.setdefault(d['id'],[])
  if d.get('alt'):self.handle_data(d['alt'])
 def handle_endtag(self,tag):
  for i in range(len(self.stack)-1,-1,-1):
   if self.stack[i][0]==tag:self.stack=self.stack[:i];break
 def handle_data(self,data):
  self.text.append(data)
  for _,ident in self.stack:
   if ident:self.anchors[ident].append(data)
def norm(s):return ' '.join(str(s).split())
def iso(s):
 x=datetime.datetime.fromisoformat(s.replace('Z','+00:00'))
 if x.tzinfo is None:raise ValueError('timestamp has no timezone')
 return x
def hashfile(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def readjson(p):return json.loads(p.read_text(encoding='utf-8-sig'))
def readcsv(p):
 with p.open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f))
def htmltext(p):
 parser=TextHTML();parser.feed(p.read_text(encoding='utf-8-sig'));return norm(' '.join(parser.text)),{k:norm(' '.join(v)) for k,v in parser.anchors.items()}
def within(root,name):
 p=(root/name).resolve()
 if not p.is_relative_to(root) or not p.is_file():raise ValueError('missing or outside workspace: '+str(name))
 return p

def gate(root,target):
 root=root.resolve();errors=[]
 def fail(phase,msg):errors.append({'phase':phase,'reason':str(msg)})
 def guarded(phase,func):
  try:return func()
  except (KeyError,ValueError,TypeError,OSError,UnicodeError,json.JSONDecodeError,csv.Error) as e:fail(phase,e);return None
 def path(name):return within(root,name)
 n=int(target[1:]);manifest=root/'gate-manifest.json'
 if not manifest.is_file():
  # Old workspaces are deliberately not accepted on their historical PASS alone.
  for ph in ['F0','F1','F2']:
   cp=root/(ph+'-checkpoint.json')
   data=guarded(ph,lambda cp=cp:readjson(cp))
   if data and not str(data.get('status','')).startswith('PASS'):fail(ph,'legacy checkpoint is not PASS')
  fail('F3','нет gate-manifest.json и подтверждённого поэлементного аудита F3')
  final=guarded('F3',lambda:readjson(path('final-checkpoint.json')))
  if final and final.get('overall')=='INCOMPLETE':fail('F3','итоговый checkpoint сообщает INCOMPLETE: '+str(final.get('reason','')))
  if n>=5:
   m=guarded('F5',lambda:readcsv(path('translation-map.csv')))
   if m:
    total=len(m);distinct=len({x.get('ru_fragment','') for x in m});fail('F5',f'{total} соответствий используют {distinct} блоковых фрагментов; отдельные цитаты и смысловая проверка не подтверждены')
   else:fail('F5','нет проверяемого поатомного соответствия')
  if n>=7:
   cross=guarded('F6',lambda:readjson(path('exam-dimension-crosswalk.json')))
   if cross and cross.get('issue'):fail('F6','зафиксирована ошибка меток замороженного экзамена: '+str(cross['issue']))
   else:fail('F6','нет проверенного frozen exam по схеме gate')
  if n>=10:
   f5=guarded('F9',lambda:readcsv(path('source-to-base-audit.csv')));f9=guarded('F9',lambda:readcsv(path('global-audit.csv')))
   if f5 and f9:
    before={x['source_id']:x.get('ru_evidence') for x in f5};copied=sum(before.get(x.get('source_id'))==x.get('evidence') for x in f9)
    fail('F9',f'{copied}/{len(f9)} свидетельств F9 совпадают с записями F5; отдельная смысловая перепроверка не подтверждена')
   else:fail('F9','нет отдельного проверяемого F9 review')
  if n>=11:
   scores=guarded('F10',lambda:readcsv(path('reader-exam-results.csv')))
   if scores:
    missing=sum(not x.get('reason') for x in scores);fail('F10',f'в {missing}/{len(scores)} строках оценок нет поля предметного обоснования')
   else:fail('F10','нет оценок с предметными обоснованиями')
  return result(target,errors)
 m=guarded('F0',lambda:readjson(manifest))
 if not isinstance(m,dict):return result(target,errors)
 if m.get('schema_version')!='step4-gate/1':fail('F0','unsupported schema_version')
 cps={};art=m.get('artifacts',{})
 for i in range(n):
  ph='F'+str(i)
  cp=guarded(ph,lambda ph=ph:readjson(path(m['checkpoints'][ph])))
  if not isinstance(cp,dict):continue
  cps[ph]=cp
  if cp.get('phase')!=ph:fail(ph,'checkpoint phase mismatch')
  pending=ph=='F5' and cp.get('status')=='SOURCE_GAPS_PENDING'
  valid=cp.get('status')=='PASS' or pending or (ph in ('F7','F8') and cp.get('status')=='NOT_APPLICABLE' and len(str(cp.get('reason','')).strip())>=20)
  if not valid:fail(ph,'checkpoint is not PASS or justified NOT_APPLICABLE')
  v=cp.get('verification',{})
  if cp.get('review')!='SELF_CHECK_ONLY' or not isinstance(v,dict) or any(not str(v.get(k,'')).strip() for k in ('criterion','expected','actual')):fail(ph,'checkpoint lacks separate SELF_CHECK_ONLY verification evidence')
  if pending and not (cp.get('source_100') is True and cp.get('translation_losses')==0 and cp.get('critical_risks')==0 and isinstance(cp.get('gap_ids'),list) and cp['gap_ids']):fail(ph,'SOURCE_GAPS_PENDING prerequisites missing')
  try:
   start,end=iso(cp['started_at']),iso(cp['completed_at'])
   if start>end:fail(ph,'completion precedes start')
  except (KeyError,ValueError,TypeError):fail(ph,'missing/invalid timezone-aware start or completion')
  evidence=cp.get('evidence')
  if not isinstance(evidence,list) or not evidence:fail(ph,'checkpoint lacks hashed evidence')
  else:
   for ev in evidence:
    try:
     if hashfile(path(ev['path']))!=ev['sha256']:fail(ph,'evidence hash mismatch: '+ev['path'])
    except (KeyError,ValueError,OSError,TypeError) as e:fail(ph,e)
  required={'F0':['rights'],'F1':['q0'],'F2':['original'],'F3':['source_ledger','f3_review'],'F4':['ru_base'],'F5':['f5_review'],'F6':['exam','exam_freeze','f6_review'],'F9':['candidate','f9_review'],'F10':['scores','f10_review']}.get(ph,[])
  paths={e.get('path') for e in evidence if isinstance(e,dict)} if isinstance(evidence,list) else set()
  for key in required:
   if art.get(key) not in paths:fail(ph,'checkpoint does not bind required artifact '+key)
  if pending:
   try:
    gapfile=cp['gap_registry']
    if gapfile not in paths:fail(ph,'gap registry is not bound to F5 checkpoint')
    gaps=readjson(path(gapfile))['gaps']
    if {x['gap_id'] for x in gaps}!=set(cp['gap_ids']) or any(not x.get('source_quote') or not x.get('question') for x in gaps):fail(ph,'gap registry lacks IDs, source quotes or research questions')
    original_text,_=htmltext(path(art['original']))
    if any(norm(x.get('source_quote','')) not in original_text for x in gaps):fail(ph,'gap source quote is not in ORIGINAL')
   except (KeyError,ValueError,OSError,TypeError) as e:fail(ph,e)
 for i in range(1,n):
  a,b='F'+str(i-1),'F'+str(i)
  if a in cps and b in cps:
   try:
    if iso(cps[b]['started_at'])<iso(cps[a]['completed_at']):fail(b,a+' → '+b+' chronology violation')
   except (KeyError,ValueError,TypeError):pass
 def artifact(key):return path(art[key])
 def review(key,phase):
  r=readjson(artifact(key))
  if r.get('review')!='SELF_CHECK_ONLY' or r.get('status')!='PASS':raise ValueError(key+': missing PASS/SELF_CHECK_ONLY')
  t=iso(r['reviewed_at'])
  if phase in cps and t>iso(cps[phase]['completed_at']):raise ValueError(key+': review later than checkpoint')
  return r
 if n>=4:
  def check_f3():
   rows=readcsv(artifact('source_ledger'));text,_=htmltext(artifact('original'));r=review('f3_review','F3');ids=[]
   for x in rows:
    sid=x['source_id'];q=norm(x['source_quote']);ids.append(sid)
    if not sid or len(q)<4 or q not in text:fail('F3','missing/invalid original quote: '+sid)
   if not ids or len(set(ids))!=len(ids):fail('F3','empty/duplicate source IDs')
   entries=r.get('entries',[]);index={x.get('source_id'):x for x in entries}
   if len(entries)!=len(ids) or set(index)!=set(ids):fail('F3','review coverage does not match source IDs')
   for sid,x in index.items():
    if len(str(x.get('reason','')).strip())<20 or x.get('verdict')!='PASS':fail('F3','missing substantive review: '+str(sid))
  guarded('F3',check_f3)
 if n>=6:
  def check_f5():
   src=readcsv(artifact('source_ledger'));r=review('f5_review','F5');_,anchors=htmltext(artifact('ru_base'));entries=r.get('entries',[]);idx={x.get('source_id'):x for x in entries};ids={x['source_id'] for x in src}
   if len(entries)!=len(ids) or set(idx)!=ids:fail('F5','F5 review must cover each unique source-ID')
   for sid,x in idx.items():
    quote=norm(x.get('ru_quote',''));loc=x.get('ru_locator','')
    if x.get('scope')!='fragment' or not loc or loc not in anchors or len(quote)<4 or quote not in anchors.get(loc,''):fail('F5','missing locatable Russian fragment: '+str(sid))
    if len(str(x.get('reason','')).strip())<20 or x.get('verdict')!='PASS':fail('F5','missing semantic self-check reason: '+str(sid))
  guarded('F5',check_f5)
 if n>=7:
  def check_f6():
   rows=readcsv(artifact('exam'));freeze=readjson(artifact('exam_freeze'));r=review('f6_review','F6')
   if freeze['sha256']!=hashfile(artifact('exam')):fail('F6','frozen exam hash mismatch')
   if set(x['dimension'] for x in rows)!=set(DIMENSIONS):fail('F6','exam must cover D1–D6')
   ids=[]
   for x in rows:
    ids.append(x['id']);d=x['dimension']
    if d not in DIMENSIONS or x.get('dimension_meaning')!=DIMENSIONS.get(d):fail('F6','incorrect D1–D6 label: '+x.get('id','?'))
    if x.get('weight') not in ('1','2','3') or not x.get('question') or not x.get('expected') or any(str(i) not in x.get('rubric','') for i in range(5)):fail('F6','incomplete question or rubric 0–4: '+x.get('id','?'))
   if not ids or len(ids)!=len(set(ids)):fail('F6','duplicate/empty exam IDs')
   checks=r.get('entries',[]);lookup={x.get('id'):x for x in checks}
   if len(checks)!=len(ids) or set(lookup)!=set(ids):fail('F6','missing separate review of each question')
   for row in rows:
    x=lookup.get(row['id'],{})
    if x.get('dimension')!=row['dimension'] or len(str(x.get('reason','')).strip())<20:fail('F6','missing dimension rationale: '+row['id'])
   if iso(freeze['frozen_at'])>iso(r['reviewed_at']):fail('F6','exam review precedes freeze')
  guarded('F6',check_f6)
 if n>=10:
  def check_f9():
   a=review('f5_review','F5');b=review('f9_review','F9');ids={x['source_id'] for x in readcsv(artifact('source_ledger'))};entries=b.get('entries',[])
   if hashfile(artifact('f5_review'))==hashfile(artifact('f9_review')) or b.get('derived_from_f5_only') is not False:fail('F9','F9 is missing an independent self-check result')
   if iso(b['reviewed_at'])<=iso(a['reviewed_at']):fail('F9','F9 review is not later than F5')
   if b.get('candidate_sha256')!=hashfile(artifact('candidate')):fail('F9','candidate hash mismatch')
   if cps.get('F5',{}).get('status')=='SOURCE_GAPS_PENDING':
    resolutions=b.get('gap_resolutions',[]);byid={x.get('gap_id'):x for x in resolutions};candidate,_=htmltext(artifact('candidate'))
    for gap in cps['F5'].get('gap_ids',[]):
     x=byid.get(gap,{});quote=norm(x.get('candidate_quote',''))
     if x.get('action') not in ('PATCH','SAFE_LIMIT') or len(quote)<4 or quote not in candidate or len(str(x.get('reason','')).strip())<20:fail('F9','source gap lacks supported resolution in candidate: '+str(gap))
   if len(entries)!=len(ids) or {x.get('source_id') for x in entries}!=ids:fail('F9','F9 review does not cover every source-ID')
   _,anchors=htmltext(artifact('candidate'))
   old={x.get('source_id'):x for x in a.get('entries',[])}
   if entries and all(x.get('reason')==old.get(x.get('source_id'),{}).get('reason') for x in entries):fail('F9','all F9 review rationales copy F5')
   for x in entries:
    loc=x.get('candidate_locator','');quote=norm(x.get('candidate_quote',''))
    if x.get('verdict')!='PASS' or len(str(x.get('reason','')).strip())<20 or not loc or loc not in anchors or len(quote)<4 or quote not in anchors.get(loc,''):fail('F9','missing substantive F9 evidence: '+str(x.get('source_id')))
  guarded('F9',check_f9)
 if n>=11:
  def check_f10():
   questions=readcsv(artifact('exam'));rows=readcsv(artifact('scores'));r=review('f10_review','F10');freeze=readjson(artifact('exam_freeze'))
   if iso(r['reviewed_at'])<=iso(freeze['frozen_at']):fail('F10','assessment precedes frozen exam')
   expected={(q['id'],v) for q in questions for v in ('ORIGINAL','BASE','CANDIDATE')};got=[]
   texts={v:htmltext(artifact(k))[0] for v,k in [('ORIGINAL','original'),('BASE','ru_base'),('CANDIDATE','candidate')]}
   for x in rows:
    key=(x['question_id'],x['version']);got.append(key);score=int(x['score'])
    if score not in range(5) or len(x.get('reason','').strip())<20 or len(norm(x.get('evidence','')))<4 or norm(x['evidence']) not in texts.get(x['version'],''):fail('F10','score lacks locatable evidence/rationale: '+str(key))
    q=next((q for q in questions if q['id']==x['question_id']),None); expected_elements=set(q['expected'].split('|')) if q else set()
    try:
     elements=json.loads(x.get('element_evidence','{}'))
     if set(elements)!=expected_elements or any(len(norm(v))<4 or norm(v) not in texts.get(x['version'],'') for v in elements.values()):fail('F10','missing evidence for expected elements: '+str(key))
    except (ValueError,TypeError):fail('F10','invalid element evidence: '+str(key))
   if len(got)!=len(expected) or set(got)!=expected:fail('F10','scores must cover each question and version exactly once')
  guarded('F10',check_f10)
 return result(target,errors)
def result(target,errors):
 errors.sort(key=lambda e:int(e['phase'][1:]));return {'status':'FAIL_GATE' if errors else 'PASS_GATE','target':target,'earliest_repair':errors[0]['phase'] if errors else None,'publication_allowed':not errors if target=='F11' else False,'errors':errors,'limitation':'Structural checks and recorded SELF_CHECK_ONLY evidence do not establish semantic truth or independent review.'}
def main():
 p=argparse.ArgumentParser();p.add_argument('--workspace',required=True);p.add_argument('--target',required=True,choices=['F'+str(i) for i in range(1,12)]);a=p.parse_args();r=gate(Path(a.workspace),a.target);print(json.dumps(r,ensure_ascii=True,indent=2));return 2 if r['errors'] else 0
if __name__=='__main__':sys.exit(main())
