import importlib.util,json,os,subprocess,time
from pathlib import Path
from types import SimpleNamespace
R=Path(__file__).resolve().parent
spec=importlib.util.spec_from_file_location('driver',R.parent/'devsecops-drone/scripts/lib/e2e_driver.py');d=importlib.util.module_from_spec(spec);spec.loader.exec_module(d)
cred=json.loads((R.parent/'devsecops-gitea/credentials.json').read_text());s=json.loads((R/'config/state.json').read_text())
a=SimpleNamespace(gitea='http://localhost:3000',drone='http://localhost:8085',user=cred['username'],password=cred['password'],token=s['token'])
env=dict(os.environ,GIT_ASKPASS=str(R/'config/askpass'),GIT_TERMINAL_PROMPT='0',MY_APP_USER=a.user,MY_APP_PASSWORD=a.password,GIT_CONFIG_COUNT='1',GIT_CONFIG_KEY_0='credential.helper',GIT_CONFIG_VALUE_0='')
repo=R/'my-app'
def git(*args):return subprocess.check_output(['git',*args],cwd=repo,env=env,text=True,stderr=subprocess.PIPE).strip()
git('commit','--allow-empty','-qm','Validate configured local Drone runner connectivity');sha=git('rev-parse','HEAD');git('push','-q')
print('Pushed '+sha,flush=True)
auth={'Authorization':'Bearer '+a.token}
for _ in range(60):
 builds=d.api('GET',a.drone+f'/api/repos/{a.user}/my-app/builds',headers=auth)
 if builds and builds[0].get('after')==sha:break
 time.sleep(2)
else:raise RuntimeError('Webhook build did not arrive')
b=d.wait_build(a,'my-app',auth,timeout=1200)
a.evidence=str(R/'evidence'/f'build-{b["number"]}');Path(a.evidence).mkdir(exist_ok=True)
steps=d.save_logs(a,'my-app',b,auth)
summary={'gitea':a.gitea,'drone':a.drone,'repository':a.user+'/my-app','commit':sha,'build':b['number'],'status':b['status'],'steps':{k:v['status'] for k,v in steps.items()}}
(R/'evidence/live-build.json').write_text(json.dumps(summary,indent=2)+'\n');print(json.dumps(summary),flush=True)
assert b['status']=='success'
