# -*- coding: utf-8 -*-

import os
import sys
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_land_service import collect_articles_by_realtor


def fetch_active_realtors(conn):
    with conn.cursor() as cur:
        cur.execute("""
            SELECT
                id,
                office_name,
                representative_name,
                phone,
                region,
                address
            FROM blog_realtors
            WHERE status = 'active'
            ORDER BY id ASC
        """)
        return cur.fetchall()


def create_search_run(conn, realtor):
    search_keyword = " ".join([
        str(realtor.get("office_name") or ""),
        str(realtor.get("representative_name") or ""),
        str(realtor.get("phone") or ""),
    ]).strip()

    search_region = str(realtor.get("region") or "").strip()

    with conn.cursor() as cur:
        cur.execute("""
            INSERT INTO blog_realtor_search_runs
            (
                realtor_id,
                search_keyword,
                search_region,
                total_found,
                matched_count,
                status,
                started_at,
                created_at
            )
            VALUES
            (
                %s,
                %s,
                %s,
                0,
                0,
                'running',
                NOW(),
                NOW()
            )
        """, (
            realtor["id"],
            search_keyword,
            search_region,
        ))

        return cur.lastrowid


def save_article(conn, realtor, run_id, article):
    with conn.cursor() as cur:
        cur.execute("""
            INSERT INTO blog_realtor_articles
            (
                realtor_id,
                search_run_id,
                article_no,
                article_name,
                trade_type,
                real_estate_type,
                price_text,
                building_name,
                floor_info,
                area_info,
                article_url,
                matched_office_name,
                matched_representative_name,
                matched_phone,
                match_score,
                collect_status,
                created_at,
                updated_at
            )
            VALUES
            (
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                'pending',
                NOW(),
                NOW()
            )
            ON DUPLICATE KEY UPDATE
                realtor_id = VALUES(realtor_id),
                search_run_id = VALUES(search_run_id),
                article_name = VALUES(article_name),
                trade_type = VALUES(trade_type),
                real_estate_type = VALUES(real_estate_type),
                price_text = VALUES(price_text),
                building_name = VALUES(building_name),
                floor_info = VALUES(floor_info),
                area_info = VALUES(area_info),
                article_url = VALUES(article_url),
                matched_office_name = VALUES(matched_office_name),
                matched_representative_name = VALUES(matched_representative_name),
                matched_phone = VALUES(matched_phone),
                match_score = VALUES(match_score),
                updated_at = NOW()
        """, (
            realtor["id"],
            run_id,
            article.get("article_no", ""),
            article.get("article_name", ""),
            article.get("trade_type", ""),
            article.get("real_estate_type", ""),
            article.get("price_text", ""),
            article.get("building_name", ""),
            article.get("floor_info", ""),
            article.get("area_info", ""),
            article.get("article_url", ""),
            article.get("matched_office_name", ""),
            article.get("matched_representative_name", ""),
            article.get("matched_phone", ""),
            int(article.get("match_score") or 0),
        ))


def update_search_run_success(conn, run_id, total_found, matched_count, message):
    with conn.cursor() as cur:
        cur.execute("""
            UPDATE blog_realtor_search_runs
            SET
                status = 'success',
                total_found = %s,
                matched_count = %s,
                error_message = %s,
                finished_at = NOW()
            WHERE id = %s
        """, (
            total_found,
            matched_count,
            message,
            run_id,
        ))


def update_search_run_failed(conn, run_id, error_message):
    with conn.cursor() as cur:
        cur.execute("""
            UPDATE blog_realtor_search_runs
            SET
                status = 'failed',
                error_message = %s,
                finished_at = NOW()
            WHERE id = %s
        """, (
            error_message,
            run_id,
        ))


def process_realtor(conn, realtor):
    run_id = create_search_run(conn, realtor)
    conn.commit()

    print("-" * 80)
    print(
        f"[RUN START] run_id={run_id}, "
        f"realtor_id={realtor['id']}, "
        f"office={realtor.get('office_name')}, "
        f"name={realtor.get('representative_name')}"
    )

    try:
        articles = collect_articles_by_realtor(realtor)

        total_found = len(articles)
        matched_count = 0

        for article in articles:
            save_article(conn, realtor, run_id, article)
            matched_count += 1

        message = f"Python 수집 완료 - 매칭 {matched_count}건"

        update_search_run_success(
            conn=conn,
            run_id=run_id,
            total_found=total_found,
            matched_count=matched_count,
            message=message,
        )

        conn.commit()

        print(f"[RUN SUCCESS] run_id={run_id}, matched={matched_count}")

    except Exception as e:
        conn.rollback()

        update_search_run_failed(conn, run_id, str(e))
        conn.commit()

        print(f"[RUN FAILED] run_id={run_id}, error={str(e)}")


def main():
    conn = get_conn()

    try:
        print("=" * 80)
        print("[START] collect_realtor_articles_job")
        print("TIME:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        print("=" * 80)

        realtors = fetch_active_realtors(conn)

        print(f"[INFO] ACTIVE REALTORS: {len(realtors)}")

        if len(realtors) == 0:
            print("[WARNING] 활성 중개사가 없습니다.")

        for realtor in realtors:
            process_realtor(conn, realtor)

        print("=" * 80)
        print("[DONE] collect_realtor_articles_job")
        print("=" * 80)

    except Exception as e:
        print("=" * 80)
        print("[FATAL ERROR]")
        print(str(e))
        print("=" * 80)

    finally:
        conn.close()


if __name__ == "__main__":
    main()