# -*- coding: utf-8 -*-

import json
import time

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"
)


class NaverArticleFetcher:

    def __init__(self, headless=False):

        self.headless = headless

        self.playwright = None
        self.browser = None
        self.context = None
        self.page = None

    def start(self):

        print("=" * 80)
        print("[BROWSER START]")

        self.playwright = sync_playwright().start()

        self.browser = self.playwright.chromium.launch(
            headless=self.headless,
            args=[
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
            ],
        )

        self.context = self.browser.new_context(
            locale="ko-KR",
            viewport={"width": 1365, "height": 900},
            user_agent=USER_AGENT,
        )

        self.page = self.context.new_page()

        self.page.goto(
            "https://new.land.naver.com/",
            wait_until="domcontentloaded",
            timeout=90000,
        )

        self.page.wait_for_timeout(3000)

        print("[NAVER LAND READY]")

    def close(self):

        print("[BROWSER CLOSE]")

        try:
            if self.browser:
                self.browser.close()
        except Exception:
            pass

        try:
            if self.playwright:
                self.playwright.stop()
        except Exception:
            pass

    def build_article_page_url(
        self,
        article_no,
        realtor_id=""
    ):

        url = (
            "https://new.land.naver.com/complexes"
            f"?articleNo={article_no}"
        )

        if realtor_id:
            url += f"&realtorId={realtor_id}"

        return url

    def open_article_page(
        self,
        article_no,
        realtor_id=""
    ):

        url = self.build_article_page_url(
            article_no,
            realtor_id,
        )

        print("[OPEN ARTICLE PAGE]")
        print(url)

        self.page.goto(
            url,
            wait_until="domcontentloaded",
            timeout=90000,
        )

        self.page.wait_for_timeout(5000)

        try:
            self.page.mouse.wheel(0, 1200)
            self.page.wait_for_timeout(1000)
        except Exception:
            pass

    def fetch_article_raw(
        self,
        article_no,
        realtor_id=""
    ):

        print("-" * 80)
        print("[FETCH ARTICLE API]", article_no)

        self.open_article_page(
            article_no,
            realtor_id,
        )

        js_code = """
        async ({ articleNo }) => {

            const url =
                `https://new.land.naver.com/api/articles/${articleNo}?complexNo=`;

            const response = await fetch(url, {
                method: "GET",
                credentials: "include",
                headers: {
                    "accept": "application/json, text/plain, */*",
                    "referer": window.location.href
                }
            });

            const text = await response.text();

            return {
                status: response.status,
                text: text
            };
        }
        """

        result = self.page.evaluate(
            js_code,
            {
                "articleNo": article_no
            }
        )

        status = result.get("status", 0)

        print("[STATUS]", status)

        if status != 200:

            return {
                "ok": False,
                "status": status,
                "error": result.get("text", "")[:1000],
                "current_url": self.page.url,
            }

        try:

            data = json.loads(
                result.get("text", "")
            )

            return {
                "ok": True,
                "data": data,
            }

        except Exception as e:

            return {
                "ok": False,
                "status": status,
                "error": str(e),
            }

    def parse_article(self, data):

        detail = data.get("articleDetail") or {}
        addition = data.get("articleAddition") or {}
        price = data.get("articlePrice") or {}
        realtor = data.get("articleRealtor") or {}

        return {
            "article_no": detail.get("articleNo", ""),
            "article_name": detail.get("articleName", ""),
            "apt_name": detail.get("aptName", ""),
            "trade_type": detail.get("tradeTypeName", ""),
            "real_estate_type": detail.get(
                "realEstateTypeName", ""
            ),
            "floor_info": addition.get("floorInfo", ""),
            "direction": addition.get("direction", ""),
            "deal_price": addition.get(
                "dealOrWarrantPrc", ""
            ),
            "rent_price": price.get("rentPrice", ""),
            "area1": detail.get("area1", ""),
            "area2": detail.get("area2", ""),
            "building_name": addition.get(
                "buildingName", ""
            ),
            "article_feature": addition.get(
                "articleFeatureDescription", ""
            ),
            "detail_description": addition.get(
                "detailDescription", ""
            ),
            "latitude": detail.get("latitude", ""),
            "longitude": detail.get("longitude", ""),
            "realtor_name": realtor.get(
                "realtorName", ""
            ),
        }

    def parse_images(self, data):

        result = []

        grand_plan_list = (
            data.get("articleDetail", {})
            .get("grandPlanList", [])
        )

        for idx, img in enumerate(grand_plan_list):

            image_url = img.get("imageSrc") or ""

            if not image_url:
                continue

            result.append({
                "image_order": idx + 1,
                "image_url": image_url,
                "image_type": "building",
            })

        return result

    def fetch_article(
        self,
        article_no,
        realtor_id=""
    ):

        raw = self.fetch_article_raw(
            article_no,
            realtor_id,
        )

        if not raw.get("ok"):

            return raw

        data = raw.get("data", {})

        article = self.parse_article(data)

        images = self.parse_images(data)

        result = {
            "ok": True,
            "article": article,
            "images": images,
            "raw": data,
        }

        print("[ARTICLE NAME]",
              article.get("article_name"))

        print("[IMAGE COUNT]",
              len(images))

        return result


def main():

    targets = [
        {
            "article_no": "2627638152",
            "realtor_id": "s5575s",
        },
        {
            "article_no": "2627446672",
            "realtor_id": "s5575s",
        },
        {
            "article_no": "2627481112",
            "realtor_id": "k3739919",
        },
    ]

    fetcher = NaverArticleFetcher(
        headless=False
    )

    fetcher.start()

    try:

        for target in targets:

            result = fetcher.fetch_article(
                article_no=target["article_no"],
                realtor_id=target["realtor_id"],
            )

            print("=" * 80)

            print(
                json.dumps(
                    result,
                    ensure_ascii=False,
                    indent=2,
                )[:3000]
            )

            time.sleep(1)

    finally:

        fetcher.close()


if __name__ == "__main__":
    main()