import json
import os
from pathlib import Path
import subprocess
import sys
from datetime import datetime
sys.path.insert(0, str(Path.cwd() / 'tools/dev'))
from common import executable, isolated_environment

folder = Path('tools/dev/runs/ligne96-captures-' + datetime.now().strftime('%H%M%S')).resolve()
folder.mkdir()
environment = isolated_environment(folder)
environment['BIGEGG_DEV_SCENE'] = 'res://tools/dev/runs/ligne96-work/cursor_probe.tscn'
environment['BIGEGG_DEV_SEED'] = '1709'
startup = subprocess.STARTUPINFO()
startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startup.wShowWindow = subprocess.SW_HIDE
command = [executable('godot'), '--path', str(Path.cwd()), '--position', '-30000,-30000',
           '--resolution', '1920x1080', '--script', str(Path('tools/dev/run_scene.gd').resolve()),
           '--', '--combat-captures=' + str(folder).replace('\\', '/')]
with (folder / 'output.log').open('w', encoding='utf-8') as log:
    process = subprocess.Popen(command, env=environment, stdout=log, stderr=subprocess.STDOUT, startupinfo=startup)
    try:
        code = process.wait(timeout=120)
    except subprocess.TimeoutExpired:
        subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'], capture_output=True)
        code = process.wait()
        print('Capture timed out')
output = (folder / 'output.log').read_text(encoding='utf-8', errors='replace')
errors = [line for line in output.splitlines() if line.startswith(('ERROR:', 'SCRIPT ERROR:', 'Parse Error:'))]
captures = [name for name in ['portrait.png', 'victoire.png'] if (folder / name).is_file()]
print(json.dumps({'exit_code': code, 'errors': errors[:12], 'captures': captures, 'folder': str(folder)}, ensure_ascii=False))
Path('tools/dev/runs/ligne96-work/capture-latest.json').write_text(json.dumps({'folder': str(folder), 'exit_code': code, 'errors': errors, 'captures': captures},ensure_ascii=False),encoding='utf-8')
sys.exit(code if code else (1 if errors or len(captures) != 2 else 0))
