"""Pinned, read-only Java inventory demonstration (Keycloak). Requires licensed scanner access or Evaluation."""
import argparse, collections, datetime, hashlib, json, os, subprocess
from pathlib import Path
SCANNER_COMMIT = '13de7361628fae4cb24100131759a0fe68f5ba5b'
TARGET_COMMIT = '4246609cf2024c85016d3fb1254c3d2533367c31'
TARGET_URL = 'https://github.com/keycloak/keycloak'
def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
def git(repo, *args): return subprocess.check_output(['git', *args], cwd=repo, text=True).strip()
def main():
    p=argparse.ArgumentParser(); p.add_argument('--scanner',type=Path,required=True); p.add_argument('--target',type=Path,required=True); p.add_argument('--output',type=Path,required=True); a=p.parse_args()
    scanner,target,out=a.scanner.resolve(),a.target.resolve(),a.output.resolve()
    for repo,expected in [(scanner,SCANNER_COMMIT),(target,TARGET_COMMIT)]:
        if git(repo,'rev-parse','HEAD')!=expected: raise SystemExit(f'Wrong revision: {repo}')
        if git(repo,'status','--porcelain','--untracked-files=no'): raise SystemExit(f'Tracked changes in {repo}; use an unmodified checkout')
    if out.exists() and any(out.iterdir()): raise SystemExit('Output must be empty')
    out.mkdir(parents=True,exist_ok=True)
    files=git(target,'ls-files').splitlines()
    manifest={'started_at_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'scanner_repository':'https://github.com/Cryptagion-io/cryptagion','scanner_commit':SCANNER_COMMIT,'target_repository':TARGET_URL,'target_commit':TARGET_COMMIT,'scope':'All tracked .java source, tests and examples; source scopes retained; vendored code excluded. No certificate or live service scan.','input_files':{f:sha(target/f) for f in files if (target/f).is_file()},'tracked_extension_counts':dict(collections.Counter(Path(f).suffix or '[none]' for f in files)),'uv_lock_sha256':sha(scanner/'uv.lock'),'commands':[]}
    policy=out/'policy.yaml'; policy.write_text('# Public-source demonstration; no deployed application or data lifetime inferred.\ndefaults:\n  classification: public\n  confidentiality_years: 0\noverrides: []\n')
    manifest['policy_sha256']=sha(policy)
    env=os.environ.copy()
    for key in ['ANTHROPIC_API_KEY','OPENAI_API_KEY','SEMGREP_APP_TOKEN']: env.pop(key,None)
    env['PATH']=str(scanner/'.venv/bin')+os.pathsep+env.get('PATH','')  # semgrep (Java analyser) lives in the scanner's locked environment
    env.update(CRYPTAGION_DB=str(out/'inventory.db'),CRYPTAGION_LICENSE=str(out/'no-license.lic'),NO_COLOR='1',COLUMNS='140',SEMGREP_SEND_METRICS='off',SEMGREP_ENABLE_VERSION_CHECK='0')
    exe=str(scanner/'.venv/bin/cryptagion')
    commands=[['scan','code','--path',str(target),'--languages','java','--include-tests','--include-examples','--exclude-vendor','--reset','--quiet','--output',str(out/'scan.json')],['risk','score','--policy',str(policy),'--classification','public','--years','0','--output',str(out/'risk.json')],['export','cbom','--repo',TARGET_URL,'--commit',TARGET_COMMIT,'--base-path',str(target),'--classification','public','--years','0','--policy',str(policy),'--output',str(out/'cbom.json')]]
    for i,cmd in enumerate(commands,1):
        r=subprocess.run([exe]+cmd,cwd=scanner,env=env,text=True,capture_output=True)
        log=f'{i:02d}-{cmd[0]}.log'; (out/log).write_text(r.stdout+'\nSTDERR:\n'+r.stderr)
        manifest['commands'].append({'args':[exe]+cmd,'exit_code':r.returncode,'log':log})
        (out/'manifest.json').write_text(json.dumps(manifest,indent=2))
        print(cmd[0],r.returncode,r.stdout[-1600:],r.stderr[-500:])
        if r.returncode: raise SystemExit(r.returncode)
        if cmd[0]=='scan':
            scan=json.loads((out/'scan.json').read_text())['scan']
            if scan['status']!='complete': raise SystemExit('Java scan incomplete: review scan.json before proceeding')
    manifest['finished_at_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat()
    manifest['output_sha256']={f.name:sha(f) for f in out.iterdir() if f.is_file() and f.name!='manifest.json'}
    (out/'manifest.json').write_text(json.dumps(manifest,indent=2))
if __name__=='__main__': main()
