"""Local ordered-candidate selection only; no search or model execution."""
from pathlib import Path
from datetime import datetime, timezone
from hashlib import sha256
from copy import deepcopy
import json,platform
HERE=Path(__file__).resolve().parent

def token(value):
 if not isinstance(value,str) or not value or value.strip()!=value:raise ValueError('exact nonempty string required')
def select(candidates,limit,cap):
 if type(limit) is not int or limit<0:raise ValueError('nonnegative integer limit required')
 if cap is not None and (type(cap) is not int or cap<1):raise ValueError('positive integer cap or null required')
 if not isinstance(candidates,list):raise ValueError('candidate list required')
 seen=set()
 for row in candidates:
  if not isinstance(row,dict) or set(row)!={'chunk_id','parent_id'}:raise ValueError('exact candidate fields required')
  token(row['chunk_id']);token(row['parent_id'])
  if row['chunk_id'] in seen:raise ValueError('duplicate chunk identity')
  seen.add(row['chunk_id'])
 selected=[];counts={}
 for row in candidates:
  if len(selected)==limit:break
  parent=row['parent_id']
  if cap is not None and counts.get(parent,0)>=cap:continue
  selected.append(row['chunk_id']);counts[parent]=counts.get(parent,0)+1
 return dict(selected_ids=selected,parent_counts=counts,parent_count=len(counts))

def main():
 data=json.loads((HERE/'fixture.json').read_text());results=[]
 for policy in data['policies']:
  actual=select(data['candidates'],policy['limit'],policy['cap'])
  assert actual==policy['expected'];results.append(dict(policy=policy['name'],**actual))
 checks=[];rows=data['candidates']
 def rejects(name,candidates,limit,cap):
  try:select(candidates,limit,cap)
  except ValueError:checks.append(name)
  else:raise AssertionError(name)
 for name,cap in [('zero_cap',0),('negative_cap',-1),('boolean_cap',True),('float_cap',1.0)]:rejects(name,rows,3,cap)
 for name,limit in [('negative_limit',-1),('boolean_limit',True),('float_limit',3.0)]:rejects(name,rows,limit,1)
 rejects('duplicate_chunk',rows+[rows[0]],3,1)
 altered=deepcopy(rows);altered[0].pop('parent_id');rejects('missing_parent',altered,3,1)
 altered=deepcopy(rows);altered[0]['parent_id']=['DEMO-A'];rejects('multi_parent_unsupported',altered,3,1)
 altered=deepcopy(rows);altered[0]['parent_id']=' DEMO-A';rejects('parent_edge_whitespace',altered,3,1)
 assert select(rows[:3],3,1)['selected_ids']==['A1'];checks.append('restricted_candidate_depth')
 assert select([],3,1)==dict(selected_ids=[],parent_counts={},parent_count=0);checks.append('empty_candidates')
 assert select(rows,0,1)==dict(selected_ids=[],parent_counts={},parent_count=0);checks.append('zero_global_limit')
 assert select(rows,3,3)==select(rows,3,None);checks.append('nonbinding_cap')
 print(json.dumps(dict(author='Anant Mishra',status='executed_offline_authored_selection',executed_at_utc=datetime.now(timezone.utc).isoformat(),python_version=platform.python_version(),sha256={n:sha256((HERE/n).read_bytes()).hexdigest() for n in ['fixture.json','reproduce.py']},results=results,boundary_checks=checks,limitations='Authored order and parent labels only. No corpus, text, relevance judgments, search service, embedding, generation, token count, quality, latency or cost measurement.'),indent=2))
if __name__=='__main__':main()
