from pathlib import Path
import os,shutil,subprocess,sys,json
base=Path(__file__).resolve().parent; repo=base/'working/repository'
if not repo.exists(): raise SystemExit('run setup_fixture.py first')
turbo=shutil.which('turbo')
if turbo is None:
    local=repo/'node_modules/.bin/turbo'
    if local.exists(): turbo=str(local.resolve())
if turbo is None:
    print(json.dumps({'status':'TURBO_UNAVAILABLE','executed':False,'network_download_attempted':False,'env_mode':'loose','cache_scope':'local:rw,remote:'})); raise SystemExit(20)
flavor=sys.argv[1] if len(sys.argv)>1 else 'vanilla'
task=sys.argv[2] if len(sys.argv)>2 else 'build'
env=os.environ.copy(); env['APP_FLAVOR']=flavor; env['TURBO_TELEMETRY_DISABLED']='1'
try:
    vr=subprocess.run([turbo,'--version'],cwd=repo,text=True,capture_output=True,timeout=10)
    turbo_version=(vr.stdout or vr.stderr).strip() or 'UNKNOWN'
except Exception:
    turbo_version='UNKNOWN'
cmd=[turbo,'run',task,'--env-mode=loose','--cache=local:rw,remote:','--ui=stream']
r=subprocess.run(cmd,cwd=repo,env=env,text=True,capture_output=True)
print(json.dumps({'status':'EXECUTED','returncode':r.returncode,'turbo_executable':str(Path(turbo).resolve()),'turbo_version':turbo_version,'flavor':flavor,'task':task,'env_mode':'loose','cache_scope':'local:rw,remote:','cwd':str(repo.resolve()),'command':cmd,'stdout':r.stdout,'stderr':r.stderr},indent=2)); raise SystemExit(r.returncode)
