from __future__ import annotations

import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SYNC = Path(__file__).with_name("multi_webzine_detail_sync.py")
SHORTS_ENQUEUE = Path(__file__).with_name("enqueue_auto_shorts.py")


def main() -> int:
    if not SYNC.is_file():
        print(f"[MULTI WEBZINE SAFE ERROR] sync script not found: {SYNC}", flush=True)
        return 0

    command = [
        sys.executable,
        "-B",
        str(SYNC),
        "--limit-per-realtor",
        "20",
        "--max-total",
        "0",
    ]
    print(
        "[MULTI WEBZINE SAFE START] limit_per_realtor=20 max_total=per_realtor_all",
        flush=True,
    )
    sync_exit_code = 1
    try:
        result = subprocess.run(command, cwd=str(ROOT), check=False)
        sync_exit_code = int(result.returncode)
    except Exception as exc:
        print(
            f"[MULTI WEBZINE SAFE WARNING] launcher_error={type(exc).__name__}: {exc}; "
            "server publishing will continue",
            flush=True,
        )

    if sync_exit_code:
        print(
            f"[MULTI WEBZINE SAFE WARNING] sync_exit_code={sync_exit_code}; "
            "정상 생성된 기사 기준으로 숏츠 등록 후 server publishing will continue",
            flush=True,
        )
    else:
        print("[MULTI WEBZINE SAFE DONE] sync_exit_code=0", flush=True)

    # 일부 기사가 실패해도 이미 정상 생성된 최신 기사로 당일 숏츠를 등록한다.
    if SHORTS_ENQUEUE.is_file():
        shorts_result = subprocess.run(
            [sys.executable, "-B", str(SHORTS_ENQUEUE)],
            cwd=str(ROOT),
            check=False,
        )
        print(
            f"[MULTI WEBZINE SHORTS ENQUEUE] sync_exit_code={sync_exit_code} "
            f"exit_code={shorts_result.returncode}",
            flush=True,
        )
    else:
        print(
            f"[MULTI WEBZINE SHORTS WARNING] enqueue script not found: {SHORTS_ENQUEUE}",
            flush=True,
        )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
