#!/usr/bin/env python3
"""YouTube 연결이 해제된 웹진 숏츠 작업을 취소하고 임시파일을 정리한다."""
from __future__ import annotations
import json,os,shutil,sys
from pathlib import Path

BASE_DIR=Path(__file__).resolve().parents[1]
if str(BASE_DIR) not in sys.path:sys.path.insert(0,str(BASE_DIR))
from db import get_conn

TEMP_ROOT=Path(os.getenv('MULTI_SHORTS_TEMP_DIR',str(BASE_DIR/'temp'/'multi_shorts')))
TERMINAL=('uploaded','cancelled','failed')

def main():
    conn=get_conn();cancelled=deleted=0
    try:
        with conn.cursor() as cur:
            cur.execute("""SELECT j.id,j.temp_file_path FROM multi_shorts_jobs j
                WHERE j.queue_status NOT IN ('uploaded','cancelled','failed')
                  AND NOT EXISTS (SELECT 1 FROM multi_shorts_oauth_accounts a
                    WHERE a.realtor_id=j.realtor_id AND a.platform='youtube'
                      AND a.account_status='connected' AND a.is_active=1)""")
            rows=cur.fetchall() or []
        for row in rows:
            path=Path(str(row.get('temp_file_path') or ''))
            if path.is_file():path.unlink();deleted+=1
            job_dir=TEMP_ROOT/f"job_{row['id']}"
            if job_dir.is_dir():shutil.rmtree(job_dir);deleted+=1
            with conn.cursor() as cur:
                cur.execute("UPDATE multi_shorts_jobs SET queue_status='cancelled',temp_file_path=NULL,error_message='YouTube 연결 해제로 자동 취소',finished_at=NOW(),updated_at=NOW() WHERE id=%s",(row['id'],))
                cur.execute("UPDATE multi_shorts_platform_posts SET upload_status='cancelled',upload_error='YouTube 연결 해제',updated_at=NOW() WHERE shorts_job_id=%s AND upload_status<>'uploaded'",(row['id'],))
                cur.execute("INSERT INTO multi_shorts_job_events (shorts_job_id,event_type,to_status,message,event_data,created_at) VALUES (%s,'youtube_disconnected','cancelled','YouTube 연결 해제로 숏츠 작업 취소',%s,NOW())",(row['id'],json.dumps({'temp_deleted':True},ensure_ascii=False)))
            conn.commit();cancelled+=1
    finally:conn.close()
    print(f'[MULTI SHORTS CONNECTION GUARD] cancelled={cancelled} deleted={deleted}',flush=True)
if __name__=='__main__':main()
