#!/usr/bin/env python3
"""
Argos QA Tester - Naver Blog Keyword Analysis Feature Test (v3)
Monitors network requests, waits for keyword analysis result
"""

import time
import json
from playwright.sync_api import sync_playwright

SCREENSHOT_DIR = "/home/jay/workspace/memory/reports/task-1933-screenshots"
BASE_URL = "http://localhost:8000/dashboard/"

results = []
network_responses = []

def log_result(status, test_name, detail=""):
    icon = {"PASS": "[PASS]", "FAIL": "[FAIL]", "WARN": "[WARN]"}.get(status, "[INFO]")
    msg = f"{icon} {test_name}"
    if detail:
        msg += f" — {detail}"
    print(msg)
    results.append({"status": status, "test": test_name, "detail": detail})

def run_tests():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()

        # Capture network responses
        def on_response(response):
            url = response.url
            if any(k in url for k in ["keyword", "naver", "blog", "analysis", "api"]):
                try:
                    status = response.status
                    network_responses.append({
                        "url": url,
                        "status": status,
                    })
                    print(f"    [NET] {status} {url}")
                except Exception:
                    pass

        page.on("response", on_response)

        # ── 1. Navigate ───────────────────────────────────────────────────────
        print("\n=== [1] Navigating to dashboard ===")
        page.goto(BASE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(5000)
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_01_loaded.png")
        log_result("PASS", "Dashboard navigation", page.url)

        # ── 2. Click 네이버블로그 tab ─────────────────────────────────────────
        print("\n=== [2] Clicking 네이버블로그 tab ===")
        try:
            tab = page.locator("button:has-text('네이버블로그')").first
            tab.wait_for(state="visible", timeout=5000)
            tab.click()
            log_result("PASS", "Click 네이버블로그 tab")
        except Exception as e:
            log_result("FAIL", "Click 네이버블로그 tab", str(e))

        page.wait_for_timeout(3000)
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_02_tab.png")

        # ── 3. Click 키워드분석 sub-tab in history to see history ─────────────
        print("\n=== [3] Switching history to 키워드분석 tab ===")
        try:
            # Use exact text match
            kwd_subtab = page.get_by_role("button", name="키워드분석")
            if kwd_subtab.count() == 0:
                kwd_subtab = page.get_by_text("키워드분석", exact=True).first
            if kwd_subtab.is_visible(timeout=2000):
                kwd_subtab.click()
                page.wait_for_timeout(1000)
                log_result("PASS", "Switch to 키워드분석 history tab")
            else:
                log_result("WARN", "키워드분석 sub-tab", "Not found")
        except Exception as e:
            log_result("WARN", "키워드분석 sub-tab", str(e))

        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_03_kwd_history.png")

        # ── 4. Type keyword ───────────────────────────────────────────────────
        print("\n=== [4] Typing '실손보험' ===")
        try:
            inp = page.locator("input[placeholder*='키워드를 입력하세요']").first
            inp.wait_for(state="visible", timeout=5000)
            inp.triple_click()
            inp.type("실손보험")
            val = inp.input_value()
            log_result("PASS", "Type keyword", f"Value: '{val}'")
        except Exception as e:
            log_result("FAIL", "Type keyword", str(e))

        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_04_typed.png")

        # ── 5. Click 분석 button ──────────────────────────────────────────────
        print("\n=== [5] Clicking 분석 button ===")
        try:
            btn = page.locator("button:has-text('분석')").first
            btn.wait_for(state="visible", timeout=3000)
            btn.click()
            log_result("PASS", "Click 분석 button")
        except Exception as e:
            log_result("FAIL", "Click 분석 button", str(e))

        # Give a moment for request to fire
        page.wait_for_timeout(1000)
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_05_analyzing.png")

        # ── 6. Poll 30s for results ───────────────────────────────────────────
        print("\n=== [6] Polling for keyword results (30s) ===")

        result_found = False
        result_type = ""
        error_found = False
        error_text = ""

        # What to look for after keyword analysis:
        # - A results table/list with keyword data (relKeyword, searchVolume, etc.)
        # - A new entry in the 키워드분석 history tab
        # - Any result container that appears

        for attempt in range(15):
            time.sleep(2)
            print(f"  Attempt {attempt+1}/15...")

            # A) Look for relKeyword in page text
            try:
                body = page.locator("body").inner_text(timeout=1000)

                # Success indicators
                success_terms = [
                    ("relKeyword", "relKeyword data"),
                    ("연관키워드", "연관키워드 section"),
                    ("월간검색수", "월간검색수 column"),
                    ("PC검색량", "PC검색량 data"),
                    ("MO검색량", "MO검색량 data"),
                    ("검색량", "검색량 data"),
                    ("경쟁정도", "경쟁정도 data"),
                ]
                for term, label in success_terms:
                    if term in body:
                        result_found = True
                        result_type = label
                        log_result("PASS", f"Keyword results visible", f"Contains: {label}")
                        break
                if result_found:
                    break

                # Error indicators specific to keyword analysis
                kwd_errors = [
                    "키워드 분석 실패",
                    "API 키",
                    "네이버 API",
                    "검색 API",
                    "Rate limit",
                    "인증 오류",
                ]
                # New error after click (check 실손보험 appeared in error)
                # Check if 실손보험 appears with an error message near it
                if "실손보험" in body:
                    lines = [l for l in body.split("\n") if "실손보험" in l]
                    if lines:
                        print(f"    Lines with '실손보험': {lines[:3]}")
                        # Check if it appeared in history (success)
                        if any("실손보험" in l for l in lines):
                            # Check nearby lines for error/success markers
                            idx = body.find("실손보험")
                            context_around = body[max(0, idx-100):idx+200]
                            print(f"    Context around '실손보험': {repr(context_around[:200])}")
                            if "✅" in context_around or "완료" in context_around:
                                result_found = True
                                result_type = "실손보험 in history as success"
                                log_result("PASS", "Keyword analysis completed", "실손보험 appears as success in history")
                                break
                            elif "❌" in context_around or "실패" in context_around:
                                error_text = context_around.strip()
                                error_found = True
                                log_result("FAIL", "Keyword analysis failed", f"Context: {error_text[:150]}")
                                break

            except Exception as e:
                print(f"    Body check error: {e}")

            # B) Check for loading state
            try:
                spinner_visible = False
                for sp in ["[class*='spin']", "[class*='loading']", "[class*='Loading']", "[class*='progress']"]:
                    s = page.locator(sp)
                    if s.count() > 0 and s.first.is_visible(timeout=200):
                        spinner_visible = True
                        break
                if spinner_visible:
                    print("    Loading spinner still visible...")
            except Exception:
                pass

        if not result_found and not error_found:
            # Final state capture
            try:
                body = page.locator("body").inner_text(timeout=2000)
                # Check if 실손보험 appeared anywhere in page
                if "실손보험" in body:
                    idx = body.find("실손보험")
                    ctx = body[max(0, idx-50):idx+300]
                    log_result("WARN", "실손보험 found in page", f"Context: {repr(ctx[:200])}")
                else:
                    log_result("WARN", "No results after 30s", "실손보험 not found in page text either")

                # Print HTML structure for debugging
                tables = page.locator("table").count()
                divs_with_class = page.evaluate("""
                    () => {
                        const elems = document.querySelectorAll('[class*="result"], [class*="keyword"], [class*="table"]');
                        return Array.from(elems).slice(0, 10).map(e => ({
                            tag: e.tagName,
                            cls: e.className.substring(0, 80),
                            text: e.innerText.substring(0, 60)
                        }));
                    }
                """)
                print(f"\n  Tables on page: {tables}")
                print(f"  Result/keyword/table elements:")
                for d in divs_with_class[:10]:
                    print(f"    <{d['tag']} class='{d['cls']}'> {repr(d['text'])}")

            except Exception as e:
                log_result("WARN", "Final state check", str(e))

        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_06_result_state.png")

        # ── 7. Table/result interactions ──────────────────────────────────────
        if result_found:
            print("\n=== [7] Testing result interactions ===")

            # Check table structure
            try:
                tables = page.locator("table")
                tc = tables.count()
                log_result("PASS" if tc > 0 else "WARN", "Results table count", f"{tc} table(s) found")

                if tc > 0:
                    # Get header texts
                    hdrs = page.locator("th").all_text_contents()
                    log_result("PASS" if hdrs else "WARN", "Table column headers", f"{hdrs[:8]}")

                    # Check for keyword-specific columns
                    kwd_cols = ["relKeyword", "monthlyPcQcCnt", "monthlyMobileQcCnt",
                                "검색량", "PC", "MO", "연관", "경쟁"]
                    found_cols = [c for c in kwd_cols if any(c in h for h in hdrs)]
                    if found_cols:
                        log_result("PASS", "Keyword data columns", f"Found: {found_cols}")
                    else:
                        log_result("WARN", "Keyword data columns", f"No keyword-specific cols in {hdrs[:6]}")

                    # Test header click (sorting)
                    for i in range(min(len(hdrs), 5)):
                        try:
                            h = page.locator("th").nth(i)
                            if h.is_visible(timeout=300):
                                h.click()
                                page.wait_for_timeout(800)
                                log_result("PASS", f"Sort by '{hdrs[i]}'", "Header clicked")
                                break
                        except Exception:
                            pass

                    page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_07_sorted.png")

                    # Row selection
                    rows = page.locator("tbody tr")
                    rc = rows.count()
                    if rc > 0:
                        rows.first.click()
                        page.wait_for_timeout(500)
                        log_result("PASS", "Row click/select", f"{rc} rows, clicked first")
                    else:
                        log_result("WARN", "Row click", "0 tbody rows")

                    page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_08_selected.png")

            except Exception as e:
                log_result("FAIL", "Table interaction", str(e))

        elif error_found:
            print(f"\n=== [ERROR] Analysis failed ===")
            print(f"  Error details: {error_text}")

        # ── 8. Check network calls ────────────────────────────────────────────
        print("\n=== [8] Network requests captured ===")
        if network_responses:
            for nr in network_responses[-10:]:
                status_label = "OK" if nr["status"] < 400 else "ERROR"
                print(f"  [{nr['status']} {status_label}] {nr['url']}")
            api_errors = [r for r in network_responses if r["status"] >= 400]
            if api_errors:
                log_result("FAIL", "API network errors", f"{len(api_errors)} failed requests")
            else:
                log_result("PASS", "Network requests", f"{len(network_responses)} relevant requests, all OK")
        else:
            log_result("WARN", "Network monitoring", "No keyword/naver/blog API requests captured")

        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_09_final.png")
        browser.close()

    # ── Summary ───────────────────────────────────────────────────────────────
    print("\n" + "="*60)
    print("FINAL TEST SUMMARY")
    print("="*60)
    pass_c = sum(1 for r in results if r["status"] == "PASS")
    fail_c = sum(1 for r in results if r["status"] == "FAIL")
    warn_c = sum(1 for r in results if r["status"] == "WARN")
    print(f"  PASS: {pass_c}  FAIL: {fail_c}  WARN: {warn_c}  TOTAL: {len(results)}")
    print("-"*60)
    for r in results:
        icon = {"PASS": "[PASS]", "FAIL": "[FAIL]", "WARN": "[WARN]"}.get(r["status"], "[INFO]")
        print(f"  {icon} {r['test']}")
        if r["detail"]:
            print(f"         {r['detail']}")
    print("="*60)

if __name__ == "__main__":
    run_tests()
