# -*- coding: utf-8 -*-

import os
import json
import time
from playwright.sync_api import sync_playwright


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG_DIR = os.path.join(BASE_DIR, "debug_outputs")
os.makedirs(DEBUG_DIR, exist_ok=True)


DEFAULT_ARTICLE_NO = "2624635265"

DEFAULT_URL = (
    "https://new.land.naver.com/complexes/104343"
    "?ms=2A3mJs,3zt7NK,16"
    "&a=APT"
    "&b=A1"
    "&e=RETAIL"
    "&articleNo=2624635265"
)


def safe_filename(url):
    return (
        url.replace("https://", "")
        .replace("http://", "")
        .replace("/", "_")
        .replace("?", "_")
        .replace("&", "_")
        .replace("=", "_")
        .replace(":", "_")
        .replace(",", "_")
    )[:180]


def main():
    article_no = input(f"articleNo 입력 기본값 {DEFAULT_ARTICLE_NO}: ").strip() or DEFAULT_ARTICLE_NO

    url = input("네이버 부동산 URL 입력, 엔터 시 기본 URL 사용: ").strip() or DEFAULT_URL

    if "{article_no}" in url:
        url = url.replace("{article_no}", article_no)

    captured = []

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=False,
            slow_mo=200,
        )

        context = browser.new_context(
            viewport={"width": 1500, "height": 1000},
            locale="ko-KR",
            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"
            ),
            extra_http_headers={
                "Accept-Language": "ko-KR,ko;q=0.9,en;q=0.8",
            }
        )

        page = context.new_page()

        def handle_response(response):
            response_url = response.url
            lower_url = response_url.lower()

            watch_words = [
                "/api/",
                "article",
                "articles",
                "complex",
                "realtor",
                "office",
                "agent",
                "land",
                "property",
            ]

            if not any(word in lower_url for word in watch_words):
                return

            try:
                status = response.status
                content_type = response.headers.get("content-type", "")

                item = {
                    "url": response_url,
                    "status": status,
                    "content_type": content_type,
                    "preview": "",
                    "json": None,
                }

                try:
                    if "json" in content_type:
                        data = response.json()
                        item["json"] = data
                        item["preview"] = json.dumps(data, ensure_ascii=False)[:3000]
                    else:
                        text = response.text()
                        item["preview"] = text[:1500]
                except Exception as e:
                    item["preview"] = f"READ_ERROR: {str(e)}"

                captured.append(item)
                print("[CAPTURED]", status, response_url)

            except Exception as e:
                print("[RESPONSE ERROR]", response_url, str(e))

        page.on("response", handle_response)

        print("=" * 100)
        print("[OPEN]", url)
        print("=" * 100)

        try:
            page.goto(url, wait_until="networkidle", timeout=90000)
        except Exception as e:
            print("[GOTO ERROR]", str(e))
            print("domcontentloaded 방식으로 재시도합니다.")
            page.goto(url, wait_until="domcontentloaded", timeout=90000)

        page.wait_for_timeout(12000)

        print("[TITLE]", page.title())
        print("[URL NOW]", page.url)

        html = page.content()

        html_path = os.path.join(
            DEBUG_DIR,
            f"playwright_page_{article_no}_{safe_filename(page.url)}.html"
        )

        with open(html_path, "w", encoding="utf-8") as f:
            f.write(html)

        print("[HTML SAVED]", html_path)

        screenshot_path = os.path.join(DEBUG_DIR, f"playwright_page_{article_no}.png")
        page.screenshot(path=screenshot_path, full_page=True)
        print("[SCREENSHOT SAVED]", screenshot_path)

        report_path = os.path.join(DEBUG_DIR, f"playwright_article_{article_no}_responses.json")

        with open(report_path, "w", encoding="utf-8") as f:
            json.dump(captured, f, ensure_ascii=False, indent=2)

        print("=" * 100)
        print("[DONE]")
        print("captured count:", len(captured))
        print("report:", report_path)
        print("=" * 100)

        input("브라우저를 닫으려면 엔터를 누르세요...")
        browser.close()


if __name__ == "__main__":
    main()