#!/usr/bin/env python3
"""
Argos QA Tester - Naver Blog Keyword Analysis Feature Test (v2)
Properly targets the 키워드분석 (keyword analysis) step, not 글작성 history
"""

import time
import sys
from playwright.sync_api import sync_playwright

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

results = []

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

        # ── 1. Navigate ───────────────────────────────────────────────────────
        print("\n=== [1] Navigating to dashboard ===")
        try:
            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)
        except Exception as e:
            log_result("FAIL", "Dashboard navigation", str(e))
            browser.close()
            return

        # ── 2. Click 네이버블로그 tab ─────────────────────────────────────────
        print("\n=== [2] Clicking 네이버블로그 tab ===")
        tab_clicked = False
        try:
            tab = page.locator("button:has-text('네이버블로그')").first
            if tab.is_visible(timeout=3000):
                tab.click()
                tab_clicked = True
                log_result("PASS", "Click 네이버블로그 tab", "button found and clicked")
            else:
                log_result("FAIL", "Click 네이버블로그 tab", "Tab button not visible")
        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_naver_tab.png")

        # ── 3. Verify we are on step 0 (키워드분석) ──────────────────────────
        print("\n=== [3] Verifying 키워드분석 step is active ===")
        try:
            # Click the 키워드분석 history sub-tab to confirm / inspect
            kwd_tab = page.locator("button:has-text('키워드분석'), text=키워드분석").first
            if kwd_tab.is_visible(timeout=2000):
                kwd_tab.click()
                page.wait_for_timeout(1000)
                log_result("PASS", "키워드분석 history sub-tab", "Sub-tab visible and clicked")
            else:
                log_result("WARN", "키워드분석 history sub-tab", "Sub-tab not found (may be already on Step 0)")
        except Exception as e:
            log_result("WARN", "키워드분석 history sub-tab", str(e))

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

        # ── 4. Type keyword ───────────────────────────────────────────────────
        print("\n=== [4] Typing '실손보험' into keyword input ===")
        input_found = False
        try:
            inp = page.locator("input[placeholder*='키워드를 입력하세요']").first
            if inp.is_visible(timeout=3000):
                inp.click()
                inp.fill("")
                inp.type("실손보험")
                val = inp.input_value()
                if "실손보험" in val:
                    input_found = True
                    log_result("PASS", "Type keyword '실손보험'", f"Input value: '{val}'")
                else:
                    log_result("FAIL", "Type keyword '실손보험'", f"Input value mismatch: '{val}'")
            else:
                log_result("FAIL", "Keyword input field", "Input not visible")
        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 ===")
        analyze_clicked = False
        try:
            btn = page.locator("button:has-text('분석')").first
            if btn.is_visible(timeout=3000):
                btn.click()
                analyze_clicked = True
                log_result("PASS", "Click 분석 button", "Button found and clicked")
            else:
                log_result("FAIL", "Click 분석 button", "Button not visible")
        except Exception as e:
            log_result("FAIL", "Click 분석 button", str(e))

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

        # ── 6. Poll for results (30s) ─────────────────────────────────────────
        print("\n=== [6] Polling for results (up to 30s) ===")
        result_found = False
        error_found = False
        error_text = ""

        # The keyword analysis results page should show a table with
        # relKeyword, searchVolume, etc. OR a loading spinner that resolves.
        # We need to wait for the Step 0 result area specifically.

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

            # 1. Check for a real data table (not just history list)
            # Try: table in main content, not inside history sidebar
            try:
                tables = page.locator("table")
                tc = tables.count()
                if tc > 0:
                    for i in range(tc):
                        t = tables.nth(i)
                        if t.is_visible(timeout=300):
                            txt = t.inner_text(timeout=300)
                            # Keyword result tables typically contain these
                            if any(k in txt for k in ["relKeyword", "검색량", "월간", "연관", "PC", "MO"]):
                                result_found = True
                                log_result("PASS", "Keyword analysis results table", f"Table #{i} has keyword data")
                                break
                    if result_found:
                        break
            except Exception:
                pass

            # 2. Check for div/list-based results with keyword data
            try:
                body_text = page.locator("main, #main, .main-content, [class*='content']").first.inner_text(timeout=500)
                if any(k in body_text for k in ["relKeyword", "연관키워드", "월간검색수", "PC검색량"]):
                    result_found = True
                    log_result("PASS", "Keyword data in main content", "Keyword columns detected in page content")
                    break
            except Exception:
                pass

            # 3. Check for loading spinner still present
            try:
                spinner = page.locator("[class*='spinner'], [class*='loading'], [class*='Loading']")
                if spinner.count() > 0 and spinner.first.is_visible(timeout=300):
                    print(f"    Still loading (spinner visible)...")
                    continue
            except Exception:
                pass

            # 4. Check for keyword-specific error in the results area
            # (NOT the history area which showed AI timeout errors)
            try:
                # Look for error specifically in the top area (step result)
                page_text = page.locator("body").inner_text(timeout=500)
                # Check if fresh error appeared (after analyze click)
                err_msgs = [
                    "API 오류", "네트워크 오류", "분석 실패", "키워드 오류",
                    "오류가 발생", "데이터를 가져오지", "네이버 API"
                ]
                for em in err_msgs:
                    if em in page_text:
                        error_found = True
                        error_text = em
                        log_result("FAIL", "Keyword analysis error", f"Error detected: '{em}'")
                        break
                if error_found:
                    break
            except Exception:
                pass

        if not result_found and not error_found:
            # Take stock of final page state
            try:
                page_text = page.locator("body").inner_text(timeout=1000)
                # Check for any result indicators
                indicators = {
                    "relKeyword": "relKeyword found",
                    "검색량": "검색량 found",
                    "연관키워드": "연관키워드 found",
                    "월간검색수": "월간검색수 found",
                    "분석 중": "Still analyzing",
                    "로딩": "Still loading",
                    "완료": "Completed",
                    "결과": "결과 found",
                }
                found_indicators = [v for k, v in indicators.items() if k in page_text]
                if found_indicators:
                    log_result("WARN", "Ambiguous results state", f"Page contains: {found_indicators}")
                else:
                    log_result("WARN", "No results detected", "Neither table nor clear error after 30s polling")
            except Exception as e:
                log_result("WARN", "Page state check", str(e))

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

        # ── 7. Scroll down to see full results ────────────────────────────────
        print("\n=== [7] Scrolling to inspect full page ===")
        page.evaluate("window.scrollTo(0, 0)")
        page.wait_for_timeout(500)
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_07_scroll_top.png")

        # Print all visible text in main area for analysis
        try:
            main_area = page.locator("main, [class*='content'], [class*='main']").first
            visible_text = main_area.inner_text(timeout=2000)
            print("\n  --- Main area text (first 800 chars) ---")
            print(visible_text[:800])
            print("  --- end ---\n")
        except Exception as e:
            print(f"  Could not read main area: {e}")
            try:
                body_text = page.locator("body").inner_text(timeout=2000)
                print("\n  --- Body text (first 800 chars) ---")
                print(body_text[:800])
                print("  --- end ---\n")
            except Exception:
                pass

        # ── 8. Check for table interactions if results found ──────────────────
        if result_found:
            print("\n=== [8] Table interaction tests ===")

            # Column headers
            try:
                headers = page.locator("th, thead td, [role='columnheader']")
                hdr_texts = headers.all_text_contents()
                log_result("PASS", "Table headers readable", f"Headers: {hdr_texts[:8]}")

                # Try sorting by clicking first clickable header
                for i in range(min(len(hdr_texts), 6)):
                    try:
                        h = headers.nth(i)
                        if h.is_visible(timeout=300):
                            h.click()
                            page.wait_for_timeout(1000)
                            log_result("PASS", f"Sort by column '{hdr_texts[i]}'", "Clicked header")
                            break
                    except Exception:
                        continue
            except Exception as e:
                log_result("WARN", "Table header interaction", str(e))

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

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

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

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

    # ── Summary ───────────────────────────────────────────────────────────────
    print("\n" + "="*60)
    print("FINAL TEST SUMMARY — Naver Blog Keyword Analysis")
    print("="*60)
    pass_count = sum(1 for r in results if r["status"] == "PASS")
    fail_count = sum(1 for r in results if r["status"] == "FAIL")
    warn_count = sum(1 for r in results if r["status"] == "WARN")
    print(f"  PASS: {pass_count}  |  FAIL: {fail_count}  |  WARN: {warn_count}  |  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()
