#!/usr/bin/env python3
"""웹진 숏츠 대본→렌더→YouTube 업로드를 한 건씩 계속 처리한다."""
import json,os,subprocess,sys,threading,time
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
from pathlib import Path

JOBS=Path(__file__).resolve().parent
STEPS=[
    'multi_homepage_build_worker.py',
    'multi_shorts_connection_guard.py',
    'multi_shorts_worker.py',
    'multi_shorts_render_worker.py',
    'multi_shorts_upload_worker.py',
]
SLEEP=max(5,int(os.getenv('MULTI_SHORTS_DAEMON_SLEEP','20')))
HEALTH_PORT=int(os.getenv('MULTI_SHORTS_DAEMON_PORT','9300'))

class Health(BaseHTTPRequestHandler):
    def do_GET(self):
        body=json.dumps({'ok':True,'service':'multi_shorts_daemon'},ensure_ascii=False).encode('utf-8')
        self.send_response(200);self.send_header('Content-Type','application/json; charset=utf-8');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
    def log_message(self,*args):pass

def main():
    server=ThreadingHTTPServer(('127.0.0.1',HEALTH_PORT),Health)
    threading.Thread(target=server.serve_forever,daemon=True).start()
    print(f'[MULTI SHORTS DAEMON START] sleep={SLEEP} health_port={HEALTH_PORT}',flush=True)
    while True:
        for name in STEPS:
            path=JOBS/name
            if not path.is_file():
                print(f'[MULTI SHORTS DAEMON WARNING] missing={path}',flush=True);continue
            result=subprocess.run([sys.executable,'-B',str(path)],cwd=str(JOBS.parent),check=False)
            if result.returncode:
                print(f'[MULTI SHORTS DAEMON STEP ERROR] worker={name} exit={result.returncode}',flush=True)
        time.sleep(SLEEP)
if __name__=='__main__':main()
