# -*- coding: utf-8 -*-

import os
import sys
import json
import argparse
from datetime import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from db import get_conn
from services.naver_article_candidate_finder_playwright import find_article_candidates_for_realtor_playwright
from services.naver_office_article_finder_playwright import find_articles_by_naver_realtor_id
from services.naver_realtor_articles_api import find_realtor_articles_by_api

def fetch_pending_runs(conn, limit=5, realtor_id=None):
    sql = """
        SELECT *
        FROM blog_realtor_search_runs
        WHERE status = 'pending'
    """
    params = []

    if realtor_id:
        sql += " AND realtor_id = %s"
        params.append(realtor_id)

    sql += " ORDER BY id ASC LIMIT %s"
    params.append(limit)

    with conn.cursor() as cur:
        cur.execute(sql, params)
        return cur.fetchall()


def fetch_realtor(conn, realtor_id):
    with conn.cursor() as cur:
        cur.execute("""
            SELECT *
            FROM blog_realtors
            WHERE id = %s
            LIMIT 1
        """, (realtor_id,))
        return cur.fetchone()


def update_run_status(conn, run_id, status, message=""):
    with conn.cursor() as cur:
        cur.execute("""
            UPDATE blog_realtor_search_runs
            SET
                status = %s,
                message = %s,
                updated_at = NOW()
            WHERE id = %s
        """, (status, message, run_id))


def update_realtor_collect_status(conn, realtor_id, status, message="", matched_count=None):
    sql = """
        UPDATE blog_realtors
        SET
            collect_status = %s,
            collect_last_message = %s,
            collect_last_at = NOW(),
            updated_at = NOW()
    """

    params = [status, message]

    if matched_count is not None:
        sql += ", collect_match_count = %s"
        params.append(matched_count)

    sql += " WHERE id = %s"
    params.append(realtor_id)

    with conn.cursor() as cur:
        cur.execute(sql, params)

def save_article_candidates(conn, run_id, realtor_id, candidates):
    saved_count = 0

    with conn.cursor() as cur:
        for item in candidates:
            article_no = str(item.get("article_no") or "").strip()

            if not article_no:
                continue

            cur.execute("""
                INSERT INTO blog_realtor_article_candidates
                (
                    search_run_id,
                    realtor_id,
                    article_no,
                    source_keyword,
                    source_url,
                    source_status_code,
                    collector,
                    match_score,
                    match_status,
                    raw_json,
                    created_at,
                    updated_at
                )
                VALUES
                (
                    %s, %s, %s, %s, %s, %s,
                    %s,
                    0, 'pending', %s, NOW(), NOW()
                )
                ON DUPLICATE KEY UPDATE
                    source_keyword = VALUES(source_keyword),
                    source_url = VALUES(source_url),
                    source_status_code = VALUES(source_status_code),
                    collector = VALUES(collector),
                    raw_json = VALUES(raw_json),
                    updated_at = NOW()
            """, (
                run_id,
                realtor_id,
                article_no,
                item.get("source_keyword", ""),
                item.get("source_url", ""),
                int(item.get("source_status_code") or 0),
                item.get("collector", ""),
                json.dumps(item, ensure_ascii=False),
            ))

            saved_count += 1

    return saved_count

def process_run(conn, run):
    run_id = run["id"]
    realtor_id = run["realtor_id"]

    print("-" * 80)
    print(f"[RUN START] run_id={run_id}, realtor_id={realtor_id}")

    realtor = fetch_realtor(conn, realtor_id)

    if not realtor:
        update_run_status(conn, run_id, "failed", "중개업소 정보를 찾을 수 없습니다.")
        conn.commit()
        print("[FAILED] realtor not found")
        return

    office_name = realtor.get("office_name", "")
    license_number = realtor.get("license_number", "")
    office_phone = realtor.get("office_phone") or realtor.get("phone") or ""
    mobile_phone = realtor.get("mobile_phone") or realtor.get("mobile") or ""

    try:
        update_run_status(conn, run_id, "running", "중개업소 기준 articleNo 후보 탐색 준비")
        update_realtor_collect_status(conn, realtor_id, "running", "articleNo 후보 탐색 중")
        conn.commit()

        print(f"[REALTOR] {office_name}")
        print(f"[LICENSE] {license_number}")
        print(f"[OFFICE PHONE] {office_phone}")
        print(f"[MOBILE PHONE] {mobile_phone}")

        # 다음 단계에서 여기에 실제 후보 수집 로직 연결
        naver_realtor_id = realtor.get("naver_realtor_id") or ""

        candidate_result = find_articles_by_naver_realtor_id(
            naver_realtor_id,
            headless=True
        )

        candidate_articles = candidate_result.get("candidates", [])
        debug_sources = candidate_result.get("debug_sources", [])
        debug_pages = candidate_result.get("debug_pages", [])

        print(f"[KEYWORDS] {candidate_result.get('keywords', [])}")
        print(f"[CANDIDATES] {len(candidate_articles)}")
        for page_info in debug_pages:
            print(
                "[API PAGE]",
                "trade=", page_info.get("trade_type"),
                "page=", page_info.get("page"),
                "count=", page_info.get("count"),
                page_info.get("url")
            )

        for src in debug_sources:
            print(
                "[SOURCE]",
                src.get("status_code"),
                src.get("html_length"),
                src.get("final_url") or src.get("url"),
                "articles:",
                src.get("article_nos")
            )

            for u in src.get("network_urls", []):
                if (
                    "article" in u
                    or "atcl" in u
                    or "list" in u
                    or "complex" in u
                    or "realtor" in u
                    or "agency" in u
                ):
                    print("   [NETWORK URL]", u)

        matched_count = len(candidate_articles)

        saved_candidate_count = save_article_candidates(
            conn,
            run_id,
            realtor_id,
            candidate_articles
        )

        print(f"[CANDIDATE SAVED] {saved_candidate_count}")

        update_run_status(
            conn,
            run_id,
            "done",
            f"후보 articleNo 탐색 완료 / 후보 {matched_count}건 / 저장 {saved_candidate_count}건",
        )

        update_realtor_collect_status(
            conn,
            realtor_id,
            "done",
            f"후보 articleNo 탐색 완료 / 후보 {matched_count}건 / 저장 {saved_candidate_count}건",
            matched_count
        )

        conn.commit()

        print(f"[DONE] run_id={run_id}, matched={matched_count}")

    except Exception as e:
        conn.rollback()

        update_run_status(conn, run_id, "failed", str(e))
        update_realtor_collect_status(conn, realtor_id, "failed", str(e))

        conn.commit()

        print(f"[FAILED] run_id={run_id}, error={str(e)}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--realtor-id", type=int, default=None)
    args = parser.parse_args()
    conn = get_conn()

    try:
        print("=" * 80)
        print("[START] process_realtor_search_runs")
        print("TIME:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        print("=" * 80)

        runs = fetch_pending_runs(conn, limit=5, realtor_id=args.realtor_id)

        print(f"[INFO] pending runs: {len(runs)}")

        for run in runs:
            process_run(conn, run)

        print("=" * 80)
        print("[DONE] process_realtor_search_runs")
        print("=" * 80)

    finally:
        conn.close()


if __name__ == "__main__":
    main()