# -*- coding: utf-8 -*-

import os
import json
import time
import argparse
from urllib.parse import urlparse, parse_qs

from playwright.sync_api import sync_playwright


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"
)


def parse_naver_url(url):
    parsed = urlparse(url)
    qs = parse_qs(parsed.query)

    article_no = qs.get("articleNo", [""])[0]

    return {
        "article_no": article_no,
    }


def build_open_url(article_no):
    return f"https://new.land.naver.com/articles/{article_no}"


def is_target_api(url, article_no):
    lower = str(url or "").lower()

    if "new.land.naver.com" not in lower:
        return False

    if "/api/" not in lower:
        return False

    targets = [
        f"/api/articles/{article_no}".lower(),
        "/schools",
        "/school",
        "/prices",
        "/price",
        "/landprice",
        "/buildinglandprice",
        "/buildings/landprice",
    ]

    return any(t in lower for t in targets)


def detect_api_type(url):
    lower = str(url or "").lower()

    if "/api/articles/" in lower:
        return "article_detail"

    if "school" in lower:
        return "school"

    if "landprice" in lower or "buildinglandprice" in lower:
        return "landprice"

    if "price" in lower:
        return "price"

    return "unknown"


def save_debug_json(article_no, captured):
    debug_dir = os.path.join(os.getcwd(), "debug")
    os.makedirs(debug_dir, exist_ok=True)

    path = os.path.join(
        debug_dir,
        f"naver_detail_related_{article_no}.json",
    )

    with open(path, "w", encoding="utf-8") as f:
        json.dump(captured, f, ensure_ascii=False, indent=2)

    print("[JSON SAVED]", path)


def print_summary(api_type, data):
    if not isinstance(data, dict):
        return

    if api_type == "article_detail":
        article_detail = data.get("articleDetail") or {}
        article_addition = data.get("articleAddition") or {}
        article_realtor = data.get("articleRealtor") or {}
        article_price = data.get("articlePrice") or {}
        land_price = data.get("landPrice") or {}

        print("[ARTICLE NAME]", article_detail.get("articleName", ""))
        print("[APT NAME]", article_detail.get("aptName", ""))
        print("[TRADE TYPE]", article_detail.get("tradeTypeName", ""))
        print("[BUILDING]", article_addition.get("buildingName", ""))
        print("[FLOOR]", article_addition.get("floorInfo", ""))
        print("[DEPOSIT/PRICE]", article_addition.get("dealOrWarrantPrc", ""))
        print("[RENT]", article_price.get("rentPrice", ""))
        print("[REALTOR]", article_realtor.get("realtorName", ""))
        print("[LAND PRICE]", land_price.get("price", ""))
        print("[EXIST TABS]", data.get("articleExistTabs", []))

    elif api_type == "school":
        print("[SCHOOL API FOUND]")
        if isinstance(data, dict):
            print("[SCHOOL KEYS]", list(data.keys())[:30])

    elif api_type == "price":
        print("[PRICE API FOUND]")
        if isinstance(data, dict):
            print("[PRICE KEYS]", list(data.keys())[:30])

    elif api_type == "landprice":
        print("[LANDPRICE API FOUND]")
        if isinstance(data, dict):
            print("[LANDPRICE KEYS]", list(data.keys())[:30])


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("--article-no", type=str, default="")
    parser.add_argument("--url", type=str, default="")
    parser.add_argument("--headless", type=int, default=0)
    parser.add_argument("--wait-sec", type=int, default=10)

    args = parser.parse_args()

    article_no = args.article_no.strip()

    if args.url:
        parsed = parse_naver_url(args.url)
        article_no = parsed.get("article_no") or article_no

    if not article_no:
        raise Exception("article_no required")

    open_url = args.url.strip() or build_open_url(article_no)

    print("=" * 80)
    print("[START] naver_detail_api_finder")
    print("[ARTICLE NO]", article_no)
    print("[OPEN URL]", open_url)
    print("=" * 80)

    captured = []
    seen_urls = set()

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=bool(args.headless),
            args=[
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
            ],
        )

        context = browser.new_context(
            locale="ko-KR",
            viewport={"width": 1365, "height": 900},
            user_agent=USER_AGENT,
        )

        page = context.new_page()

        def handle_response(response):
            try:
                response_url = response.url

                if not is_target_api(response_url, article_no):
                    return

                if response_url in seen_urls:
                    return

                seen_urls.add(response_url)

                status = response.status
                content_type = response.headers.get("content-type", "").lower()
                api_type = detect_api_type(response_url)

                print("-" * 80)
                print("[TARGET API]", api_type, status)
                print(response_url)

                item = {
                    "api_type": api_type,
                    "url": response_url,
                    "status": status,
                    "content_type": content_type,
                    "json": None,
                    "text_preview": "",
                }

                try:
                    text = response.text()
                    item["text_preview"] = text[:1200]

                    if "application/json" in content_type:
                        data = json.loads(text)
                        item["json"] = data

                        if isinstance(data, dict):
                            print("[JSON KEYS]", list(data.keys())[:30])
                        elif isinstance(data, list):
                            print("[JSON LIST]", len(data))

                        print_summary(api_type, data)

                except Exception as e:
                    item["parse_error"] = str(e)
                    print("[PARSE ERROR]", str(e))

                captured.append(item)

            except Exception as e:
                print("[RESPONSE ERROR]", str(e))

        page.on("response", handle_response)

        try:
            page.goto(
                open_url,
                wait_until="domcontentloaded",
                timeout=90000,
            )

            page.wait_for_timeout(3000)

            # 화면 스크롤: 추가 API 호출 유도
            for amount in [1200, 1800, 2400, -1200, 2600]:
                try:
                    page.mouse.wheel(0, amount)
                    page.wait_for_timeout(1200)
                except Exception:
                    pass

            # 탭 버튼 클릭 시도: 학군/시세/공시가격 API 호출 유도
            click_keywords = [
                "시세",
                "실거래",
                "가격",
                "공시가격",
                "동호수",
                "학군",
                "학교",
            ]

            for keyword in click_keywords:
                try:
                    locator = page.get_by_text(keyword, exact=False)
                    count = locator.count()

                    if count > 0:
                        print("[CLICK TRY]", keyword)
                        locator.first.click(timeout=3000)
                        page.wait_for_timeout(2500)

                except Exception:
                    pass

            time.sleep(max(1, int(args.wait_sec)))

        finally:
            browser.close()

    print("=" * 80)
    print("[CAPTURED TARGET API COUNT]", len(captured))

    save_debug_json(article_no, captured)

    print("[DONE]")


if __name__ == "__main__":
    main()