# -*- coding: utf-8 -*-

import time
import random
import requests
from urllib.parse import quote

from playwright.sync_api import sync_playwright


BASE_HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/136.0.0.0 Safari/537.36"
    ),
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "ko-KR,ko;q=0.9,en;q=0.8",
    "Referer": "https://new.land.naver.com/",
    "Connection": "keep-alive",
}


def build_api_url(realtor_id, page=1):
    realtor_id = quote(str(realtor_id).strip())

    return (
        "https://new.land.naver.com/api/articles"
        f"?realtorId={realtor_id}"
        f"&page={int(page)}"
        "&order=rank"
        "&tradeType="
        "&realEstateType="
        "&isFixed=false"
    )


def create_land_session(
    headless=True,
):
    """
    Playwright 1회 실행 후
    네이버부동산 쿠키를 requests.Session으로 이관
    """

    pw = sync_playwright().start()

    browser = pw.chromium.launch(
        headless=headless,
        args=[
            "--disable-blink-features=AutomationControlled",
            "--no-sandbox",
        ],
    )

    context = browser.new_context(
        locale="ko-KR",
        viewport={"width": 1365, "height": 900},
        user_agent=BASE_HEADERS["User-Agent"],
    )

    page = context.new_page()

    print("[BOOTSTRAP] open naver land")

    page.goto(
        "https://new.land.naver.com/",
        wait_until="domcontentloaded",
        timeout=60000,
    )

    page.wait_for_timeout(4000)

    cookies = context.cookies()

    session = requests.Session()

    session.headers.update(BASE_HEADERS)

    for cookie in cookies:
        try:
            session.cookies.set(
                cookie["name"],
                cookie["value"],
                domain=cookie.get("domain"),
            )
        except Exception:
            pass

    print(f"[COOKIE COUNT] {len(cookies)}")

    return {
        "pw": pw,
        "browser": browser,
        "context": context,
        "page": page,
        "session": session,
    }


def close_land_session(env):
    try:
        env["context"].close()
    except Exception:
        pass

    try:
        env["browser"].close()
    except Exception:
        pass

    try:
        env["pw"].stop()
    except Exception:
        pass


def extract_candidates(article_list):
    results = []

    for item in article_list:
        article_no = (
            item.get("articleNo")
            or item.get("atclNo")
            or ""
        )

        article_no = str(article_no).strip()

        if not article_no:
            continue

        results.append({
            "article_no": article_no,
            "article_name": item.get("articleName", ""),
            "trade_type": item.get("tradeTypeName", ""),
            "real_estate_type": item.get("realEstateTypeName", ""),
            "price_text": item.get("dealOrWarrantPrc", ""),
            "floor_info": item.get("floorInfo", ""),
            "area_info": item.get("areaName", ""),
            "direction": item.get("direction", ""),
            "article_feature_desc": item.get("articleFeatureDesc", ""),
        })

    return results


def fetch_latest_article(
    session,
    realtor_id,
    page=1,
):
    url = build_api_url(
        realtor_id=realtor_id,
        page=page,
    )

    print("[REQUEST]", realtor_id, url)

    try:
        response = session.get(
            url,
            timeout=20,
        )

        status = response.status_code

        print("[STATUS]", status)

        if status != 200:
            return {
                "ok": False,
                "status": status,
                "article_no": "",
                "candidates": [],
                "error": response.text[:500],
            }

        data = response.json()

        article_list = (
            data.get("articleList")
            or data.get("list")
            or []
        )

        candidates = extract_candidates(article_list)

        latest_article_no = ""

        if candidates:
            latest_article_no = candidates[0]["article_no"]

        return {
            "ok": True,
            "status": status,
            "article_no": latest_article_no,
            "candidates": candidates,
        }

    except Exception as e:
        return {
            "ok": False,
            "error": str(e),
            "article_no": "",
            "candidates": [],
        }


def fetch_multiple_realtors(
    realtor_ids,
    headless=True,
    delay_min=0.8,
    delay_max=2.0,
):
    env = create_land_session(
        headless=headless,
    )

    session = env["session"]

    results = []

    try:
        for idx, realtor_id in enumerate(realtor_ids, start=1):

            print("=" * 80)
            print(f"[{idx}/{len(realtor_ids)}] REALTOR: {realtor_id}")

            result = fetch_latest_article(
                session=session,
                realtor_id=realtor_id,
                page=1,
            )

            results.append({
                "realtor_id": realtor_id,
                "result": result,
            })

            sleep_sec = random.uniform(
                delay_min,
                delay_max,
            )

            print(f"[SLEEP] {sleep_sec:.2f} sec")

            time.sleep(sleep_sec)

    finally:
        close_land_session(env)

    return results


if __name__ == "__main__":

    realtor_ids = [
        "s5575s",
        "hope6130066",
        "k3739919",
    ]

    results = fetch_multiple_realtors(
        realtor_ids=realtor_ids,
        headless=False,
    )

    print("=" * 80)
    print("[FINAL RESULT]")

    for item in results:
        print(item)