#!/usr/bin/env python3
"""
Argos QA - Debug why keyword input loses value / button not triggering API
"""

import time
from playwright.sync_api import sync_playwright

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

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

        console_msgs = []
        page.on("console", lambda msg: console_msgs.append(f"[{msg.type}] {msg.text}"))

        page.goto(BASE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(5000)

        # Click tab
        tab = page.locator("button:has-text('네이버블로그')").first
        tab.click()
        page.wait_for_timeout(3000)

        # Inspect the input element
        input_info = page.evaluate("""
            () => {
                const inp = document.querySelector('input[placeholder*="키워드를 입력하세요"]');
                if (!inp) return {found: false};
                return {
                    found: true,
                    type: inp.type,
                    value: inp.value,
                    disabled: inp.disabled,
                    readOnly: inp.readOnly,
                    parentClass: inp.parentElement?.className?.substring(0, 80),
                    reactFiber: !!inp._reactFiber || !!(inp.__reactFiber),
                    // Check if React is managing this
                    hasReactProps: Object.keys(inp).some(k => k.startsWith('__react'))
                };
            }
        """)
        print(f"Input info: {input_info}")

        # Try to type and observe
        inp = page.locator("input[placeholder*='키워드를 입력하세요']").first
        inp.click()

        # Try React-compatible input using dispatchEvent
        # First, let's see what happens with fill vs type
        print("\n--- Method 1: .fill() ---")
        inp.fill("실손보험")
        val1 = inp.input_value()
        print(f"After fill(): value='{val1}'")

        # Check React state
        react_val = page.evaluate("""
            () => {
                const inp = document.querySelector('input[placeholder*="키워드를 입력하세요"]');
                if (!inp) return 'input not found';
                // Try to find React internal state
                const keys = Object.keys(inp);
                const reactKey = keys.find(k => k.startsWith('__reactFiber') || k.startsWith('_reactFiber'));
                if (reactKey) {
                    try {
                        let fiber = inp[reactKey];
                        while (fiber && fiber.tag !== 0) {
                            if (fiber.memoizedState && fiber.memoizedState.queue) {
                                return 'React fiber found';
                            }
                            fiber = fiber.return;
                        }
                    } catch(e) { return 'fiber error: ' + e.message; }
                }
                return 'React key: ' + (reactKey || 'none') + ', DOM value: ' + inp.value;
            }
        """)
        print(f"React state check: {react_val}")

        # Find the 분석 button and check its disabled state
        btn_info = page.evaluate("""
            () => {
                const btns = document.querySelectorAll('button');
                for (const btn of btns) {
                    if (btn.textContent.includes('분석') && !btn.textContent.includes('경쟁')) {
                        return {
                            text: btn.textContent.trim(),
                            disabled: btn.disabled,
                            className: btn.className.substring(0, 80),
                            opacity: window.getComputedStyle(btn).opacity,
                            cursor: window.getComputedStyle(btn).cursor
                        };
                    }
                }
                return {found: false};
            }
        """)
        print(f"\nButton info before click: {btn_info}")

        # Now try triggering via keyboard Enter instead of button click
        print("\n--- Method 2: Press Enter in input ---")
        inp.click()
        inp.fill("")
        inp.fill("실손보험")
        val_before_enter = inp.input_value()
        print(f"Before Enter: value='{val_before_enter}'")
        inp.press("Enter")
        time.sleep(3)
        val_after_enter = inp.input_value()
        print(f"After Enter: value='{val_after_enter}'")
        page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_debug_enter.png")

        # Check if API was called
        print("\n--- Method 3: React nativeInputValueSetter ---")
        # Use React's native input value setter to properly trigger onChange
        success = page.evaluate("""
            () => {
                const inp = document.querySelector('input[placeholder*="키워드를 입력하세요"]');
                if (!inp) return false;
                // Use React's native value setter
                const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
                    window.HTMLInputElement.prototype, 'value'
                ).set;
                nativeInputValueSetter.call(inp, '실손보험');
                inp.dispatchEvent(new Event('input', { bubbles: true }));
                inp.dispatchEvent(new Event('change', { bubbles: true }));
                return inp.value;
            }
        """)
        print(f"After React setter: '{success}'")
        time.sleep(1)
        val_react = inp.input_value()
        print(f"Input value after React setter: '{val_react}'")

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

        # Try clicking button now
        btn = page.locator("button:has-text('분석')").first
        btn_disabled = btn.evaluate("el => el.disabled")
        btn_opacity = btn.evaluate("el => window.getComputedStyle(el).opacity")
        print(f"\nButton state: disabled={btn_disabled}, opacity={btn_opacity}")

        if not btn_disabled:
            btn.click()
            time.sleep(5)
            # Check if API called
            body = page.locator("body").inner_text(timeout=1000)
            print(f"After button click body sample: {body[:300]}")
            page.screenshot(path=f"{SCREENSHOT_DIR}/03_keyword_debug_after_click.png")
        else:
            print("Button is disabled! Input value not recognized by React")

        # Console errors
        print(f"\nConsole messages ({len(console_msgs)}):")
        for m in console_msgs[-10:]:
            print(f"  {m}")

        browser.close()

if __name__ == "__main__":
    run_debug()
