# -*- coding: utf-8 -*-
"""
STEP102-09
tools/ensure_missing_realtor_maps.py

map_image_url이 비어 있는 신규/기존 중개사를 찾아
tools/generate_realtor_naver_map.py 를 자동 실행한다.

목적:
- 신규 중개사 등록 후 지도 이미지가 누락되는 문제 보완
- 초안 생성 전에 지도 이미지가 준비되도록 운영 파이프라인에 끼워 넣기

사용:
cd /d D:\honghee\blog_api
python tools\ensure_missing_realtor_maps.py --limit 50

특정 중개사만:
python tools\ensure_missing_realtor_maps.py --realtor-id 5
"""

import argparse
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from db import get_conn


PYTHON = sys.executable
MAP_TOOL = ROOT / "tools" / "generate_realtor_naver_map.py"


def fetch_targets(conn, limit=50, realtor_id=None):
    params = []

    where = """
        (map_image_url IS NULL OR map_image_url = '')
        AND naver_realtor_id IS NOT NULL
        AND naver_realtor_id <> ''
    """

    if realtor_id:
        where += " AND id = %s"
        params.append(realtor_id)

    sql = f"""
        SELECT
            id,
            office_name,
            naver_realtor_id,
            map_image_url
        FROM blog_realtors
        WHERE {where}
        ORDER BY id DESC
        LIMIT %s
    """
    params.append(limit)

    with conn.cursor() as cur:
        cur.execute(sql, params)
        return cur.fetchall()


def get_realtor(conn, realtor_id):
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT id, office_name, naver_realtor_id, map_image_url
            FROM blog_realtors
            WHERE id = %s
            LIMIT 1
            """,
            (realtor_id,),
        )
        return cur.fetchone()


def run_map_generator(realtor_id):
    if not MAP_TOOL.exists():
        raise FileNotFoundError(f"map tool not found: {MAP_TOOL}")

    cmd = [
        PYTHON,
        str(MAP_TOOL),
        "--realtor-id",
        str(realtor_id),
    ]

    print("[MAP GENERATE RUN]", " ".join(cmd))

    return subprocess.run(
        cmd,
        cwd=str(ROOT),
        text=True,
        capture_output=True,
        timeout=180,
    )


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--limit", type=int, default=50)
    parser.add_argument("--realtor-id", type=int, default=None)
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    conn = get_conn()

    try:
        targets = fetch_targets(
            conn,
            limit=args.limit,
            realtor_id=args.realtor_id,
        )

        print(f"[TARGETS] {len(targets)}")

        if not targets:
            print("[DONE] no missing realtor maps")
            return

        success = 0
        failed = 0

        for row in targets:
            realtor_id = row.get("id") if isinstance(row, dict) else row[0]
            office_name = row.get("office_name") if isinstance(row, dict) else row[1]
            naver_realtor_id = row.get("naver_realtor_id") if isinstance(row, dict) else row[2]

            print("-" * 80)
            print(f"[TARGET] id={realtor_id} office={office_name} naver_realtor_id={naver_realtor_id}")

            if args.dry_run:
                continue

            try:
                result = run_map_generator(realtor_id)

                if result.stdout:
                    print(result.stdout.strip())

                if result.stderr:
                    print("[STDERR]", result.stderr.strip())

                after = get_realtor(conn, realtor_id)
                map_image_url = after.get("map_image_url") if isinstance(after, dict) else after[3]

                if result.returncode == 0 and map_image_url:
                    success += 1
                    print(f"[MAP READY] id={realtor_id} map_image_url={map_image_url}")
                else:
                    failed += 1
                    print(f"[MAP FAILED] id={realtor_id} returncode={result.returncode} map_image_url={map_image_url}")

            except Exception as e:
                failed += 1
                print(f"[MAP ERROR] id={realtor_id} err={e}")

        print("=" * 80)
        print(f"[DONE] success={success} failed={failed}")

    finally:
        conn.close()


if __name__ == "__main__":
    main()
