"""Execute the original two cases once after root confirms frozen app readiness."""
import datetime as dt
import hashlib
import json
from pathlib import Path
import time
import urllib.error
import urllib.request
import uuid

OUT=Path(__file__).resolve().parent
LAB=Path('D:/uAgentKit-lab/anythingllm-20261002')
AUTHORIZATION=LAB/'control/generation-authorized'
if not AUTHORIZATION.exists():
    raise RuntimeError('Root readiness confirmation is required before model-case execution')
freeze=json.loads((OUT/'frozen-readiness.json').read_text(encoding='utf-8'))
assert hashlib.sha256(Path(__file__).read_bytes()).hexdigest()==freeze['harnessSources']['run-cases.py']
for filename,digest in freeze['harnessSources'].items():
    assert hashlib.sha256((OUT/filename).read_bytes()).hexdigest()==digest,filename+' changed after freeze'
ready=json.loads((OUT/'ingestion-readiness-attempt-2.json').read_text(encoding='utf-8'))
for docs in ready['fixture'].values():
    for document in docs:
        assert hashlib.sha256(Path(document['path']).read_bytes()).hexdigest()==document['sha256']
base=json.loads((OUT/'preparation-services.json').read_text(encoding='utf-8'))['endpoints']['server']
key=None
key_id=None
API_CALLS=[]
def call(label,method,route,data=None,authenticated=True,retain=True):
    headers={'Content-Type':'application/json'}
    if authenticated:
        headers['Authorization']='Bearer '+key
    body=json.dumps(data).encode() if data is not None else None
    started=dt.datetime.now(dt.timezone.utc)
    start=time.monotonic()
    request=urllib.request.Request(base+route,data=body,method=method,headers=headers)
    try:
        response=urllib.request.urlopen(request,timeout=300)
    except urllib.error.HTTPError as error:
        response=error
    with response:
        status=response.status
        raw=response.read()
    try:
        result=json.loads(raw)
    except json.JSONDecodeError:
        result={'unparsedBody':raw.decode('utf-8',errors='replace')}
    entry={'label':label,'startedAt':started.isoformat(),'finishedAt':dt.datetime.now(dt.timezone.utc).isoformat(),'durationSeconds':round(time.monotonic()-start,4),'method':method,'route':route,'request':data,'httpStatus':status,'response':result if retain else {'credentialResponseWithheld':True},'headersRetained':False}
    API_CALLS.append(entry)
    (OUT/'case-api-calls.json').write_text(json.dumps(API_CALLS,indent=2),encoding='utf-8')
    return entry,result
questions=freeze['caseQuestions']
result={'startedAt':dt.datetime.now(dt.timezone.utc).isoformat(),'cases':{},'credentialValueRetained':False,'scope':'Original AnythingLLM local document revision/citation and injection-boundary cases. Query mode, default prompt, local providers, no tools or MCP.'}
try:
    _,created=call('create-case-api-key','POST','/api/system/generate-api-key',{'name':'uagentkit-anythingllm-original-case-only'},authenticated=False,retain=False)
    key=created['apiKey']['secret']
    key_id=created['apiKey']['id']
    for case,items in questions.items():
        result_file=OUT/(case+'-case.json')
        if result_file.exists():
            raise RuntimeError('Refusing to repeat existing '+case+' case')
        (LAB/'control/current-case').write_text(case,encoding='utf-8')
        slug=ready['workspaces'][case]['slug']
        started=dt.datetime.now(dt.timezone.utc)
        calls=[]
        _,snapshot=call(case+'-workspace-before','GET',f'/api/v1/workspace/{slug}')
        before=hashlib.sha256((LAB/'unimported/private-note.txt').read_bytes()).hexdigest()
        for name,message in items:
            payload={'message':message,'mode':'query','sessionId':'uagentkit-'+case+'-'+name+'-'+uuid.uuid4().hex,'attachments':[],'reset':True}
            entry,response=call(case+'-'+name,'POST',f'/api/v1/workspace/{slug}/chat',payload)
            calls.append(entry)
            print(json.dumps({'case':case,'question':name,'httpStatus':entry['httpStatus'],'durationSeconds':entry['durationSeconds'],'type':response.get('type'),'sourceCount':len(response.get('sources',[])),'error':response.get('error')}),flush=True)
        after=hashlib.sha256((LAB/'unimported/private-note.txt').read_bytes()).hexdigest()
        case_result={'case':case,'startedAt':started.isoformat(),'finishedAt':dt.datetime.now(dt.timezone.utc).isoformat(),'calls':calls,'workspaceBefore':snapshot,'unimportedFileBeforeSha256':before,'unimportedFileAfterSha256':after,'unimportedFileUnchanged':before==after,'evaluation':'Pending explicit output, citation and trace review; HTTP200 alone is not a pass'}
        result_file.write_text(json.dumps(case_result,indent=2),encoding='utf-8')
        result['cases'][case]={'path':result_file.name,'apiQuestions':len(calls),'apiHTTPStatuses':[c['httpStatus'] for c in calls]}
except Exception as error:
    result['executionError']={'type':type(error).__name__,'message':str(error)}
    raise
finally:
    if key_id is not None:
        entry,_=call('revoke-case-api-key','DELETE',f'/api/system/api-key/{key_id}',authenticated=False)
        result['taskApiKeyRevoked']=entry['httpStatus']==200
    key=None
    (LAB/'control/current-case').write_text('preparation',encoding='utf-8')
    result['finishedAt']=dt.datetime.now(dt.timezone.utc).isoformat()
    (OUT/'case-execution-summary.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
    print(json.dumps(result,indent=2),flush=True)
