#!/usr/bin/env python3
import json
import os
import shlex
import subprocess
import time
import urllib.request
from pathlib import Path

ROOT = Path('/data/video-pipeline/HaTramAudio/project/012-Nguoi-Giu-Chiec-Chia-Khoa-Cua-Ngay-Hom-Qua')
RUN_ID = 'run-20260720T084924Z-02f78a49'
LEASE = '/home/hermes/.hermes/skills/audio-production/ha-tram-audio/scripts/gate_lease.py'
ENV = Path.home() / '.config/ha-tram-audio/worker.env'


def load_env(path):
    values = {}
    for raw in path.read_text().splitlines():
        line = raw.strip()
        if line and not line.startswith('#') and '=' in line:
            key, value = line.split('=', 1)
            values[key.strip()] = value.strip().strip('"\'')
    return values


def health(port):
    with urllib.request.urlopen(f'http://192.168.1.104:{port}/health', timeout=15) as response:
        return json.load(response)


while True:
    states = {port: health(port) for port in (8022, 8023, 8024)}
    running = {port: data.get('running') or [] for port, data in states.items()}
    if all(not jobs for jobs in running.values()):
        print(json.dumps({'worker_idle': True, 'running': running}), flush=True)
        break
    print(json.dumps({'worker_idle': False, 'running': running}), flush=True)
    subprocess.check_call([
        'python3', LEASE, 'heartbeat', '--project-root', str(ROOT), '--gate', 'intro',
        '--run-id', RUN_ID, '--ttl-seconds', '7200',
    ], stdout=subprocess.DEVNULL)
    time.sleep(30)

env = load_env(ENV)
host = env['WORKER_HOST']
user = env['WORKER_USER']
password = env['WORKER_PASSWORD']
poster = ROOT / 'image/normalized/intro-poster-1920x1080.png'
audio = ROOT / 'audio/intro-full.wav'
outdir = ROOT / 'output/intro'
outdir.mkdir(parents=True, exist_ok=True)
temp = outdir / '.intro.tmp.mp4'
output = outdir / 'intro.mp4'
if output.exists():
    raise SystemExit('intro output already exists before this run')
remote = f'''set -euo pipefail
D=$(ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 {shlex.quote(str(audio))})
ffmpeg -hide_banner -loglevel error -y -loop 1 -framerate 30 -i {shlex.quote(str(poster))} -i {shlex.quote(str(audio))} -t "$D" -map 0:v:0 -map 1:a:0 -c:v h264_nvenc -preset p4 -tune hq -rc vbr -cq 21 -b:v 0 -profile:v high -level:v 4.0 -pix_fmt yuv420p -r 30 -video_track_timescale 15360 -c:a aac -b:a 192k -ar 48000 -ac 1 -movflags +faststart {shlex.quote(str(temp))}
ffprobe -v error -show_streams -show_format -of json {shlex.quote(str(temp))}
mv {shlex.quote(str(temp))} {shlex.quote(str(output))}
'''
cmd = ['sshpass', '-p', password, 'ssh', '-o', 'StrictHostKeyChecking=accept-new',
       f'{user}@{host}', 'bash', '-lc', shlex.quote(remote)]
subprocess.check_call(cmd)
subprocess.check_call([
    'python3', LEASE, 'heartbeat', '--project-root', str(ROOT), '--gate', 'intro',
    '--run-id', RUN_ID, '--ttl-seconds', '7200',
], stdout=subprocess.DEVNULL)
print(json.dumps({'status': 'completed', 'output': str(output)}), flush=True)
