#!/usr/bin/env python3
"""
Argos QA Tester - Naver Blog Keyword Analysis Feature Test (FINAL)
Tests the complete 키워드분석 workflow on the 네이버블로그 tab
"""

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 = []
api_calls = []

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()

        # Network monitoring
        def on_request(request):
            url = request.url
            if "naver-blog" in url or "keyword" in url.lower():
                api_calls.append({"type": "request", "method": request.method, "url": url})
                print(f"    [REQ] {request.method} {url}")

        def on_response(response):
            url = response.url
            if "naver-blog" in url or "keyword" in url.lower():
                status = response.status
                api_calls.append({"type": "response", "status": status, "url": url})
                print(f"    [RES] {status} {url}")
                if status >= 400:
                    try:
                        body = response.text()
                        print(f"    [ERR BODY] {body[:300]}")
                    except Exception:
                        pass

        page.on("request", on_request)
        page.on("response", on_response)

        # ── 1. Navigate ───────────────────────────────────────────────────────
        print("\n=== [1] Navigate to http://localhost:8000/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] Click 네이버블로그 tab ===")
        try:
            tab = page.locator("button:has-text('네이버블로그')").first
            tab.wait_for(state="visible", timeout=5000)
            tab.click()
            log_result("PASS", "Click 네이버블로그 tab", "button:has-text('네이버블로그')")
        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_active.png")

        # ── 3. Switch history to 키워드분석 sub-tab ───────────────────────────
        print("\n=== [3] Switch history to 키워드분석 sub-tab ===")
        try:
            # History sub-tabs: 키워드분석 / 글작성 / 경쟁분석
            kwd_subtab = page.get_by_role("button", name="키워드분석")
            if kwd_subtab.count() > 0 and kwd_subtab.first.is_visible(timeout=2000):
                kwd_subtab.first.click()
                page.wait_for_timeout(1000)
                log_result("PASS", "Switch to 키워드분석 history sub-tab")
            else:
                # Also try text-based
                kwd_subtab2 = page.get_by_text("키워드분석").first
                if kwd_subtab2.is_visible(timeout=1000):
                    kwd_subtab2.click()
                    page.wait_for_timeout(1000)
                    log_result("PASS", "Switch to 키워드분석 history sub-tab", "via get_by_text")
                else:
                    log_result("WARN", "키워드분석 sub-tab", "Not found or not visible")
        except Exception as e:
            log_result("WARN", "키워드분석 sub-tab", str(e))

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

        # ── 4. Type '실손보험' in keyword input ───────────────────────────────
        print("\n=== [4] Type '실손보험' in keyword input ===")
        try:
            inp = page.locator("input[placeholder*='키워드를 입력하세요']").first
            inp.wait_for(state="visible", timeout=5000)
            # Clear and type
            inp.click()
            # Select all and replace
            inp.press("Control+a")
            inp.press("Delete")
            inp.fill("실손보험")
            val = inp.input_value()
            if "실손보험" in val:
                log_result("PASS", "Type keyword '실손보험'", f"Input value confirmed: '{val}'")
            else:
                log_result("FAIL", "Type keyword '실손보험'", f"Value was: '{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] Click 분석 button ===")
        try:
            btn = page.locator("button:has-text('분석')").first
            btn.wait_for(state="visible", timeout=3000)
            # Verify input still has value
            inp_val = page.locator("input[placeholder*='키워드를 입력하세요']").first.input_value()
            print(f"  Input value before click: '{inp_val}'")
            btn.click()
            log_result("PASS", "Click 분석 button", f"input was: '{inp_val}'")
        except Exception as e:
            log_result("FAIL", "Click 분석 button", str(e))

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

        # ── 6. Poll 30 seconds for results ───────────────────────────────────
        print("\n=== [6] Polling for results (30s, every 2s) ===")

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

        for attempt in range(15):
            time.sleep(2)
            elapsed = (attempt + 1) * 2
            print(f"  [{elapsed}s] Polling attempt {attempt+1}/15...")

            try:
                body_text = page.locator("body").inner_text(timeout=1000)

                # ── Check for keyword analysis result data ──
                # Primary success: relKeyword column data (Naver API response format)
                kwd_data_terms = [
                    "relKeyword", "monthlyPcQcCnt", "monthlyMobileQcCnt",
                    "compIdx", "plAvgDepth",
                    "월간검색수", "PC검색량", "MO검색량", "연관키워드", "경쟁정도",
                ]
                for term in kwd_data_terms:
                    if term in body_text:
                        result_found = True
                        result_type = f"keyword data: '{term}'"
                        log_result("PASS", "Keyword analysis results appeared",
                                   f"'{term}' found in page at {elapsed}s")
                        break
                if result_found:
                    break

                # ── Check if 실손보험 appeared in history (completed) ──
                if "실손보험" in body_text:
                    idx = body_text.find("실손보험")
                    ctx = body_text[max(0, idx-80):idx+200]
                    print(f"    '실손보험' found in page. Context: {repr(ctx[:150])}")
                    # Check for completion indicators
                    if "✅" in ctx or ("실손보험" in ctx and "실패" not in ctx and "오류" not in ctx):
                        result_found = True
                        result_type = "실손보험 in history (success)"
                        log_result("PASS", "Keyword analysis completed",
                                   f"실손보험 visible in history at {elapsed}s")
                        break
                    elif "❌" in ctx or "실패" in ctx or "오류" in ctx:
                        error_text = ctx.strip()
                        error_found = True
                        log_result("FAIL", "Keyword analysis error",
                                   f"Error at {elapsed}s: {error_text[:150]}")
                        break

                # ── Check for any result table ──
                tables = page.locator("table").count()
                if tables > 0:
                    result_found = True
                    result_type = f"table element ({tables} tables)"
                    log_result("PASS", "Results table appeared", f"{tables} table(s) at {elapsed}s")
                    break

                # ── Check for loading indicator ──
                loading = page.locator("[class*='spinner'], [class*='loading']")
                if loading.count() > 0:
                    try:
                        vis = loading.first.is_visible(timeout=200)
                        if vis:
                            print(f"    Still loading...")
                    except Exception:
                        pass

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

        # Save result screenshot
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_06_results.png")

        if not result_found and not error_found:
            # Detailed page inspection
            try:
                body_text = page.locator("body").inner_text(timeout=2000)
                print(f"\n  --- Page text sample (chars 0-1000) ---")
                print(body_text[:1000])
                print(f"  ---")

                # Check DOM structure
                structure = page.evaluate("""
                    () => {
                        const all = document.querySelectorAll('*');
                        const interesting = [];
                        for (const el of all) {
                            const cls = el.className || '';
                            const txt = (el.innerText || '').trim().substring(0, 50);
                            if ((cls.includes('result') || cls.includes('keyword') ||
                                 cls.includes('table') || cls.includes('data')) && txt) {
                                interesting.push({
                                    tag: el.tagName,
                                    cls: typeof cls === 'string' ? cls.substring(0, 60) : '',
                                    txt: txt
                                });
                            }
                        }
                        return interesting.slice(0, 15);
                    }
                """)
                if structure:
                    print("\n  DOM elements with result/keyword/table/data classes:")
                    for s in structure:
                        print(f"    <{s['tag']} class='{s['cls']}'> {repr(s['txt'])}")
                else:
                    print("\n  No DOM elements with result/keyword/table/data classes found")

                # Check if any API call was made
                kwd_api_calls = [c for c in api_calls if "naver-blog" in c["url"]]
                if kwd_api_calls:
                    print(f"\n  Naver Blog API calls made: {len(kwd_api_calls)}")
                    for c in kwd_api_calls:
                        print(f"    {c}")
                else:
                    print("\n  No naver-blog API calls detected during analysis!")

                log_result("WARN", "Keyword analysis no results after 30s",
                           "No keyword data, table, or result appeared")
            except Exception as e:
                log_result("WARN", "Final state inspection", str(e))

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

            # Check for table
            tables = page.locator("table")
            tc = tables.count()
            print(f"  Tables found: {tc}")

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

                # Keyword columns check
                kwd_cols = {
                    "relKeyword": "연관 키워드",
                    "searchVolume": "검색량",
                    "PC": "PC 검색",
                    "MO": "모바일 검색",
                    "경쟁": "경쟁도",
                }
                found = [v for k, v in kwd_cols.items() if any(k in h for h in hdrs)]
                if found:
                    log_result("PASS", "Keyword data columns present", f"{found}")
                else:
                    log_result("WARN", "Keyword data columns", f"Not found in headers: {hdrs[:8]}")

                # Test sort by clicking headers
                sort_done = False
                for i in range(min(len(hdrs), 6)):
                    try:
                        h = page.locator("th").nth(i)
                        if h.is_visible(timeout=300) and hdrs[i].strip():
                            h.click()
                            page.wait_for_timeout(1000)
                            sort_done = True
                            log_result("PASS", f"Click header '{hdrs[i]}' for sorting")
                            break
                    except Exception:
                        pass
                if not sort_done:
                    log_result("WARN", "Column header sort", "No clickable header found")

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

                # Row selection
                rows = page.locator("tbody tr")
                rc = rows.count()
                if rc > 0:
                    try:
                        rows.first.click()
                        page.wait_for_timeout(500)
                        log_result("PASS", "Keyword row selection", f"Clicked first of {rc} rows")
                    except Exception as e:
                        log_result("WARN", "Keyword row selection", str(e))
                else:
                    log_result("WARN", "Keyword rows", "tbody has 0 rows")

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

            else:
                # Non-table results (list/cards)
                result_items = page.locator(
                    "[class*='result'] > *, [class*='keyword'] > *, [class*='item']"
                )
                ic = result_items.count()
                log_result("PASS" if ic > 0 else "WARN",
                           "Result items",
                           f"{ic} result items found (non-table format)")

                if ic > 0:
                    result_items.first.click()
                    page.wait_for_timeout(500)
                    page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_07_item_click.png")

        elif error_found:
            log_result("FAIL", "Keyword analysis result", f"Error: {error_text[:200]}")

        # ── 8. API summary ────────────────────────────────────────────────────
        print("\n=== [8] API Call Summary ===")
        naver_calls = [c for c in api_calls if "naver-blog" in c["url"]]
        if naver_calls:
            for c in naver_calls:
                status_str = str(c.get("status", "?"))
                icon = ("OK" if (int(status_str) < 400) else "ERR") if status_str.isdigit() else "?"
                print(f"  [{c['type'].upper()}] {c.get('method', '')} {c['url']} {status_str if 'status' in c else ''}")

            analyze_calls = [c for c in naver_calls
                             if "analyz" in c["url"] or "keyword" in c["url"]]
            if analyze_calls:
                log_result("PASS", "Keyword analysis API was called",
                           f"{len(analyze_calls)} calls to analyze/keyword endpoints")
            else:
                history_calls = [c for c in naver_calls if "history" in c["url"]]
                log_result("WARN", "No analyze/keyword API call",
                           f"Only history calls: {len(history_calls)}")
        else:
            log_result("WARN", "No naver-blog API calls captured", "Check network filter")

        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_09_final.png")
        print(f"\n  Final screenshot: 03_keyword_09_final.png")
        browser.close()

    # ── Final Summary ─────────────────────────────────────────────────────────
    print("\n" + "="*65)
    print("  FINAL QA REPORT: Naver Blog Keyword Analysis")
    print("="*65)
    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"\n  PASS: {pass_c}  |  FAIL: {fail_c}  |  WARN: {warn_c}  |  TOTAL: {len(results)}\n")
    print("-"*65)
    for r in results:
        icon = {"PASS": "[PASS]", "FAIL": "[FAIL]", "WARN": "[WARN]"}.get(r["status"], "[INFO]")
        print(f"  {icon} {r['test']}")
        if r["detail"]:
            detail_lines = r["detail"].split("\n")
            for dl in detail_lines[:3]:
                if dl.strip():
                    print(f"           {dl.strip()}")
    print("="*65)

if __name__ == "__main__":
    run_tests()
