#!/usr/bin/env python3
"""Launch/resume the cross-split auxiliary branch and enforce the disk reserve."""
import argparse
from datetime import datetime
import json
import hashlib
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import time
from zoneinfo import ZoneInfo

ROOT = Path(__file__).resolve().parents[1]


def alive(pid):
    try:
        return Path(f'/proc/{pid}/stat').read_text().split(') ', 1)[1][0] != 'Z'
    except FileNotFoundError:
        return False


def write(path, data):
    temporary = path.with_suffix('.tmp')
    temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n')
    temporary.replace(path)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', default='configs/human_correction_7086.json')
    parser.add_argument('--watch-pid', type=int)
    args = parser.parse_args()
    config_path = (ROOT/args.config).resolve()
    config = json.loads(config_path.read_text())
    output = Path(config['output'])
    output.mkdir(parents=True, exist_ok=True)
    if args.watch_pid is not None:
        paused = False
        while alive(args.watch_pid):
            low_disk = shutil.disk_usage(ROOT).free < 50*2**30
            if low_disk and not paused:
                os.killpg(args.watch_pid, signal.SIGSTOP)
                paused = True
                write(output/'disk_reserve_status.json', {'state':'paused_for_disk_reserve',
                    'reason':'Available space below 50 GiB; entire workflow process group suspended',
                    'checked_at':datetime.now(ZoneInfo('Asia/Shanghai')).isoformat()})
            elif not low_disk and paused:
                os.killpg(args.watch_pid, signal.SIGCONT)
                paused = False
                write(output/'disk_reserve_status.json', {'state':'resumed_disk_reserve_available',
                    'checked_at':datetime.now(ZoneInfo('Asia/Shanghai')).isoformat()})
            time.sleep(30)
        return
    for key in ('all_frames_reviewed_by_user', 'unchanged_proposals_accepted_after_manual_review',
                'empty_frames_confirmed_negative_by_user'):
        if config.get(key) is not True:
            raise SystemExit(f'Label confirmation is still pending: {key}; training has not started')
    if (output/'delivery_manifest.json').exists():
        imported = json.loads((output/'manual_import_manifest.json').read_text())
        for name, digest in imported['input_binding'].items():
            if hashlib.sha256(Path(name).read_bytes()).hexdigest() != digest:
                raise SystemExit('Completed workflow input changed; select a new output version')
        print('Delivery already complete:', output/'delivery_manifest.json')
        return
    state_path = output/'workflow_process.json'
    if state_path.exists() and alive(json.loads(state_path.read_text())['pid']):
        raise SystemExit('This workflow is already running; refusing duplicate training')
    if shutil.disk_usage(ROOT).free < 50*2**30:
        raise SystemExit('Cannot start with less than 50 GiB available')
    env = {**os.environ, 'OMP_NUM_THREADS':'4', 'MKL_NUM_THREADS':'4', 'PYTHONUNBUFFERED':'1',
           'PYTHONPATH': str(ROOT)+os.pathsep+os.environ.get('PYTHONPATH','')}
    command = [sys.executable, '-m', 'pallet.mixed_manual_assistant', '--config', str(config_path)]
    with (output/'workflow.log').open('a') as log:
        process = subprocess.Popen(command, cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
            stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
    write(state_path, {'pid':process.pid, 'command':command, 'config':str(config_path),
          'started_at':datetime.now(ZoneInfo('Asia/Shanghai')).isoformat()})
    with (output/'watchdog.log').open('a') as log:
        watchdog = subprocess.Popen([sys.executable, str(Path(__file__).resolve()),
            '--config', str(config_path), '--watch-pid', str(process.pid)], cwd=ROOT,
            stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
    write(output/'watchdog_process.json', {'pid':watchdog.pid, 'workflow_pid':process.pid})
    print(json.dumps({'workflow_pid':process.pid,'watchdog_pid':watchdog.pid,
                     'log':str(output/'workflow.log')},ensure_ascii=False))


if __name__ == '__main__':
    main()
