#!/usr/bin/env python3
"""
Argos QA Tester - Naver Blog Keyword Analysis Feature Test
Task: Test the 네이버블로그 keyword analysis feature on dashboard
"""

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 to dashboard ──────────────────────────────────────────
        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_dashboard_loaded.png")
            log_result("PASS", "Dashboard navigation", f"URL: {page.url}")
        except Exception as e:
            log_result("FAIL", "Dashboard navigation", str(e))
            browser.close()
            return

        # ── 2. Click 네이버블로그 tab ──────────────────────────────────────────
        print("\n=== [2] Clicking 네이버블로그 tab ===")
        try:
            # Try various selectors for the tab
            tab_selectors = [
                "button:has-text('네이버블로그')",
                "text=네이버블로그",
                "[role='tab']:has-text('네이버블로그')",
                "a:has-text('네이버블로그')",
                "li:has-text('네이버블로그')",
                "div:has-text('네이버블로그')",
            ]
            tab_clicked = False
            for sel in tab_selectors:
                try:
                    elem = page.locator(sel).first
                    if elem.is_visible(timeout=2000):
                        elem.click()
                        tab_clicked = True
                        log_result("PASS", "Click 네이버블로그 tab", f"selector: {sel}")
                        break
                except Exception:
                    continue

            if not tab_clicked:
                # Dump all button/tab texts for debugging
                buttons = page.locator("button, [role='tab'], a, li").all_text_contents()
                log_result("WARN", "Click 네이버블로그 tab", f"Tab not found. Available texts: {buttons[:20]}")

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

        except Exception as e:
            log_result("FAIL", "Click 네이버블로그 tab", str(e))
            page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_02_naver_tab_error.png")

        # ── 3. Type keyword into input ────────────────────────────────────────
        print("\n=== [3] Typing keyword '실손보험' ===")
        try:
            # Try placeholder-based selector
            input_selectors = [
                "input[placeholder*='키워드를 입력하세요']",
                "textarea[placeholder*='키워드를 입력하세요']",
                "input[placeholder*='키워드']",
                "input[type='text']",
                "input[type='search']",
                "[placeholder*='키워드']",
            ]
            input_found = False
            for sel in input_selectors:
                try:
                    elem = page.locator(sel).first
                    if elem.is_visible(timeout=2000):
                        elem.click()
                        elem.fill("실손보험")
                        input_found = True
                        log_result("PASS", "Type keyword '실손보험'", f"selector: {sel}")
                        break
                except Exception:
                    continue

            if not input_found:
                log_result("FAIL", "Type keyword '실손보험'", "Input field not found")
                page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_03_input_error.png")
            else:
                page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_03_keyword_typed.png")

        except Exception as e:
            log_result("FAIL", "Type keyword '실손보험'", str(e))

        # ── 4. Click 분석 button ──────────────────────────────────────────────
        print("\n=== [4] Clicking 분석 button ===")
        try:
            analyze_selectors = [
                "button:has-text('분석')",
                "input[value='분석']",
                "[type='submit']",
                "button[type='submit']",
                "text=분석",
            ]
            analyze_clicked = False
            for sel in analyze_selectors:
                try:
                    elem = page.locator(sel).first
                    if elem.is_visible(timeout=2000):
                        elem.click()
                        analyze_clicked = True
                        log_result("PASS", "Click 분석 button", f"selector: {sel}")
                        break
                except Exception:
                    continue

            if not analyze_clicked:
                all_buttons = page.locator("button").all_text_contents()
                log_result("FAIL", "Click 분석 button", f"Button not found. Available buttons: {all_buttons}")
                page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_04_analyze_error.png")
            else:
                page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_04_analyze_clicked.png")

        except Exception as e:
            log_result("FAIL", "Click 분석 button", str(e))

        # ── 5. Wait up to 30 seconds for results ──────────────────────────────
        print("\n=== [5] Waiting for results (up to 30s) ===")
        result_found = False
        error_found = False
        error_text = ""

        table_selectors = [
            "table",
            "[role='table']",
            ".results-table",
            ".keyword-results",
            "tbody tr",
            "[class*='result']",
            "[class*='table']",
        ]
        error_selectors = [
            "[class*='error']",
            "[class*='Error']",
            ".error-message",
            "[role='alert']",
            "text=오류",
            "text=에러",
            "text=실패",
            "text=Error",
        ]

        for attempt in range(15):  # 15 attempts x 2s = 30s
            time.sleep(2)
            print(f"  Polling attempt {attempt + 1}/15...")

            # Check for results table
            for sel in table_selectors:
                try:
                    elems = page.locator(sel)
                    if elems.count() > 0 and elems.first.is_visible(timeout=500):
                        result_found = True
                        log_result("PASS", "Results appeared", f"selector: {sel}, attempt: {attempt+1}")
                        break
                except Exception:
                    continue

            if result_found:
                break

            # Check for error
            for sel in error_selectors:
                try:
                    elems = page.locator(sel)
                    if elems.count() > 0:
                        try:
                            error_text = elems.first.inner_text(timeout=500)
                            if error_text.strip():
                                error_found = True
                                log_result("FAIL", "Error appeared", f"Error text: {error_text[:200]}")
                                break
                        except Exception:
                            pass
                except Exception:
                    continue

            if error_found:
                break

        if not result_found and not error_found:
            log_result("WARN", "Waiting for results", "Neither results table nor error found after 30s")

        # ── 6. Screenshot after results ───────────────────────────────────────
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_05_results.png")
        print(f"  Screenshot saved: 03_keyword_05_results.png")

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

            # Check for keyword data columns
            data_columns = ["relKeyword", "searchVolume", "키워드", "검색량", "월간검색수", "연관키워드"]
            found_columns = []
            for col in data_columns:
                try:
                    elems = page.locator(f"text={col}")
                    if elems.count() > 0:
                        found_columns.append(col)
                except Exception:
                    pass

            if found_columns:
                log_result("PASS", "Keyword data columns present", f"Found: {found_columns}")
            else:
                # Check all table header texts
                try:
                    headers = page.locator("th, thead td, [role='columnheader']").all_text_contents()
                    log_result("WARN", "Keyword data columns", f"Headers found: {headers[:10]}")
                except Exception as e:
                    log_result("WARN", "Keyword data columns", f"Could not read headers: {e}")

            # Test column header sorting
            print("  Testing column header sorting...")
            sort_clicked = False
            try:
                headers = page.locator("th, thead td, [role='columnheader']")
                count = headers.count()
                if count > 0:
                    for i in range(min(count, 5)):
                        try:
                            hdr = headers.nth(i)
                            if hdr.is_visible(timeout=500):
                                hdr_text = hdr.inner_text(timeout=500)
                                hdr.click()
                                page.wait_for_timeout(1000)
                                sort_clicked = True
                                log_result("PASS", f"Clicked column header for sorting", f"Column: '{hdr_text}'")
                                break
                        except Exception:
                            continue
            except Exception as e:
                log_result("WARN", "Column header sorting", str(e))

            if not sort_clicked:
                log_result("WARN", "Column header sorting", "No sortable column headers found")

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

            # Test selecting/clicking keywords in results
            print("  Testing keyword row selection...")
            row_clicked = False
            try:
                row_selectors = [
                    "tbody tr",
                    "[role='row']",
                    "table tr:not(:first-child)",
                    ".result-row",
                    "[class*='row']",
                ]
                for sel in row_selectors:
                    try:
                        rows = page.locator(sel)
                        count = rows.count()
                        if count > 0:
                            first_row = rows.first
                            if first_row.is_visible(timeout=500):
                                first_row.click()
                                page.wait_for_timeout(1000)
                                row_clicked = True
                                log_result("PASS", "Clicked keyword row", f"selector: {sel}, rows: {count}")
                                break
                    except Exception:
                        continue
            except Exception as e:
                log_result("WARN", "Keyword row click", str(e))

            if not row_clicked:
                log_result("WARN", "Keyword row click", "Could not click any result rows")

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

            # Check row count
            try:
                row_count = page.locator("tbody tr").count()
                if row_count > 0:
                    log_result("PASS", "Results table has data rows", f"Row count: {row_count}")
                else:
                    log_result("WARN", "Results table data rows", "Table exists but has 0 rows")
            except Exception as e:
                log_result("WARN", "Results table row count", str(e))

        elif error_found:
            print(f"\n=== [ERROR DOCUMENTED] ===")
            log_result("FAIL", "Analysis returned error", f"Error: {error_text[:300]}")
            page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_06_error_state.png")

        # ── Final page state screenshot ────────────────────────────────────────
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_08_final_state.png")

        browser.close()

    # ── Summary ───────────────────────────────────────────────────────────────
    print("\n" + "="*60)
    print("TEST SUMMARY")
    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}")
    print(f"  FAIL: {fail_count}")
    print(f"  WARN: {warn_count}")
    print(f"  TOTAL: {len(results)}")
    print("="*60)
    for r in results:
        status_icon = {"PASS": "[PASS]", "FAIL": "[FAIL]", "WARN": "[WARN]"}.get(r["status"], "[INFO]")
        print(f"  {status_icon} {r['test']}")
        if r["detail"]:
            print(f"         {r['detail']}")

if __name__ == "__main__":
    run_tests()
