# -*- coding: utf-8 -*-

import re
import time
import random
from playwright.sync_api import sync_playwright


def uniq_keep_order(items):
    seen = set()
    result = []

    for item in items:
        item = str(item or "").strip()

        if not item or item in seen:
            continue

        seen.add(item)
        result.append(item)

    return result


def extract_article_nos_from_text(text):
    text = str(text or "")

    patterns = [
        r'"articleNo"\s*:\s*"([0-9]{8,})"',
        r'"articleNo"\s*:\s*([0-9]{8,})',
        r'"atclNo"\s*:\s*"([0-9]{8,})"',
        r'"atclNo"\s*:\s*([0-9]{8,})',
        r'"articleNumber"\s*:\s*"([0-9]{8,})"',
        r'"articleNumber"\s*:\s*([0-9]{8,})',
    ]

    results = []

    for pattern in patterns:
        results.extend(re.findall(pattern, text, flags=re.I))

    return uniq_keep_order(results)


def fetch_api_text_with_page(page, api_url):
    result = page.evaluate(
        """
        async (url) => {
            const res = await fetch(url, {
                method: 'GET',
                credentials: 'include',
                headers: {
                    'accept': 'application/json,text/plain,*/*'
                }
            });

            const text = await res.text();

            return {
                status: res.status,
                url: res.url,
                text: text
            };
        }
        """,
        api_url
    )

    return result


def find_realtor_articles_by_api(realtor_id, max_pages=30):
    realtor_id = str(realtor_id or "").strip()

    if not realtor_id:
        return {
            "ok": False,
            "error": "단체아이디가 없습니다.",
            "candidates": [],
            "debug_pages": [],
        }

    all_articles = []
    debug_pages = []

    trade_types = [
        "",
        "A1",
        "B1",
        "B2",
    ]

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=[
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
            ]
        )

        context = browser.new_context(
            locale="ko-KR",
            viewport={"width": 1365, "height": 900},
            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"
            )
        )

        page = context.new_page()

        # 먼저 네이버 부동산에 진입해 세션/쿠키를 만든다.
        entry_url = f"https://new.land.naver.com/offices?realtorId={realtor_id}"

        try:
            page.goto(
                entry_url,
                wait_until="domcontentloaded",
                timeout=60000
            )
            page.wait_for_timeout(3000)
        except Exception:
            pass

        for trade_type in trade_types:
            empty_count = 0

            for page_no in range(1, max_pages + 1):
                api_url = (
                    "https://new.land.naver.com/api/articles"
                    f"?realtorId={realtor_id}"
                    f"&page={page_no}"
                    f"&order=rank"
                    f"&tradeType={trade_type}"
                    f"&realEstateType="
                    f"&isFixed=false"
                )

                try:
                    time.sleep(random.uniform(0.25, 0.7))

                    result = fetch_api_text_with_page(page, api_url)

                    status = int(result.get("status") or 0)
                    final_url = result.get("url") or api_url
                    text = result.get("text") or ""

                    article_nos = extract_article_nos_from_text(text)

                    print(
                        "[PLAYWRIGHT API]",
                        "trade=", trade_type,
                        "page=", page_no,
                        "status=", status,
                        "count=", len(article_nos)
                    )

                    debug_pages.append({
                        "url": final_url,
                        "trade_type": trade_type,
                        "real_estate_type": "",
                        "page": page_no,
                        "status": status,
                        "count": len(article_nos),
                        "article_nos": article_nos,
                        "text_sample": text[:500],
                    })

                    if status != 200:
                        break

                    if not article_nos:
                        empty_count += 1
                    else:
                        empty_count = 0

                    for article_no in article_nos:
                        all_articles.append({
                            "article_no": article_no,
                            "source_keyword": realtor_id,
                            "source_url": final_url,
                            "source_status_code": status,
                            "collector": "playwright_article_api",
                            "trade_type": trade_type,
                            "real_estate_type": "",
                            "page": page_no,
                        })

                    if empty_count >= 2:
                        break

                except Exception as e:
                    debug_pages.append({
                        "url": api_url,
                        "trade_type": trade_type,
                        "real_estate_type": "",
                        "page": page_no,
                        "status": 0,
                        "count": 0,
                        "article_nos": [],
                        "error": str(e),
                    })
                    break

        context.close()
        browser.close()

    unique = {}

    for item in all_articles:
        article_no = str(item.get("article_no") or "").strip()

        if article_no and article_no not in unique:
            unique[article_no] = item

    return {
        "ok": True,
        "naver_realtor_id": realtor_id,
        "candidates": list(unique.values()),
        "debug_pages": debug_pages,
    }