# test_authenticated_v2.py — UI 로그인 시도 + 비인증 상태 최대 검증
from playwright.sync_api import sync_playwright
import os, json, requests, time

SCREENSHOT_DIR = "/home/jay/workspace/memory/screenshots/insuro-e2e"
BASE_URL = "http://127.0.0.1:5173"
SUPABASE_URL = "https://zayhfjuwviporbzokudr.supabase.co"
SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InpheWhmanV3dmlwb3Jiem9rdWRyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzMwNDY1MTksImV4cCI6MjA4ODYyMjUxOX0.aRQpYgl5ZeHxh4PTnVm_1Hwky2h83-Cb_8RGlv-xP9s"

results = []
all_console_errors = []
login_success = False
auth_method = None

test_passwords = ["insuro2024!", "InsUr0Test!", "test1234!", "password123"]
session_data = None

# Step 1: Try Supabase REST API
for pwd in test_passwords:
    try:
        resp = requests.post(
            f"{SUPABASE_URL}/auth/v1/token?grant_type=password",
            headers={"apikey": SUPABASE_KEY, "Content-Type": "application/json"},
            json={"email": "drumband@gmail.com", "password": pwd},
            timeout=10
        )
        if resp.status_code == 200:
            session_data = resp.json()
            login_success = True
            auth_method = f"REST API (password: {pwd})"
            print(f"[REST] Login succeeded: {pwd}")
            break
        else:
            print(f"[REST] Failed ({pwd}): {resp.status_code} - {resp.text[:80]}")
    except Exception as e:
        print(f"[REST] Error: {e}")

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True, args=["--no-sandbox"])

    # ===== DESKTOP CONTEXT =====
    context = browser.new_context(viewport={"width": 1280, "height": 720})
    page = context.new_page()
    page.on("console", lambda msg: all_console_errors.append({
        "type": msg.type, "text": msg.text, "url": page.url
    }) if msg.type == "error" else None)

    # --- Step 2: Try UI login if REST failed ---
    if not login_success:
        print("[UI] Attempting UI login via /login page...")
        try:
            page.goto(BASE_URL + "/login", wait_until="networkidle", timeout=15000)
            page.wait_for_timeout(1500)
            page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-00-login-page.png"), full_page=True)

            # Find email/password fields
            email_sel = 'input[type="email"], input[name="email"], input[placeholder*="이메일"], input[placeholder*="email" i]'
            pwd_sel = 'input[type="password"]'

            email_el = page.query_selector(email_sel)
            pwd_el = page.query_selector(pwd_sel)

            if email_el and pwd_el:
                for pwd in test_passwords:
                    page.fill(email_sel, "drumband@gmail.com")
                    page.fill(pwd_sel, pwd)

                    # Find submit button
                    submit_sel = 'button[type="submit"], button:has-text("로그인"), button:has-text("Login"), button:has-text("Sign in")'
                    submit_el = page.query_selector(submit_sel)
                    if submit_el:
                        submit_el.click()
                    else:
                        page.keyboard.press("Enter")

                    page.wait_for_timeout(3000)
                    current_url = page.url

                    if "/login" not in current_url:
                        login_success = True
                        auth_method = f"UI login (password: {pwd})"
                        print(f"[UI] Login SUCCESS with: {pwd}")
                        page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-01-after-login.png"), full_page=True)
                        break
                    else:
                        print(f"[UI] Login FAILED with: {pwd}")
                        # Check for error message
                        err_text = page.inner_text("body")[:300]
                        print(f"  Page text: {err_text[:150]}")
                        # Re-navigate for next attempt
                        if pwd != test_passwords[-1]:
                            page.goto(BASE_URL + "/login", wait_until="networkidle", timeout=10000)
                            page.wait_for_timeout(1000)
            else:
                print("[UI] Could not find email/password fields")
                print(f"  Page text: {page.inner_text('body')[:500]}")
        except Exception as e:
            print(f"[UI] Login error: {e}")

    # --- Step 3: If REST succeeded, inject session ---
    if login_success and session_data and auth_method and "REST" in auth_method:
        page.goto(BASE_URL + "/login", wait_until="networkidle", timeout=15000)
        page.wait_for_timeout(1000)
        storage_key = "sb-zayhfjuwviporbzokudr-auth-token"
        storage_value = json.dumps({
            "access_token": session_data.get("access_token"),
            "refresh_token": session_data.get("refresh_token"),
            "token_type": "bearer",
            "expires_in": session_data.get("expires_in", 3600),
            "expires_at": session_data.get("expires_at"),
            "user": session_data.get("user"),
        })
        page.evaluate(f'window.localStorage.setItem("{storage_key}", JSON.stringify({storage_value}))')
        page.wait_for_timeout(500)
        print("[INJECT] Session injected via localStorage")

    # --- Step 4: Verify auth state ---
    page.goto(BASE_URL + "/intro", wait_until="networkidle", timeout=15000)
    page.wait_for_timeout(3000)
    intro_url = page.url
    auth_working = "/login" not in intro_url

    results.append({
        "check": "auth_state",
        "login_success": login_success,
        "auth_method": auth_method,
        "intro_redirected_to_login": not auth_working,
        "final_url_after_intro_nav": intro_url
    })

    if auth_working:
        print(f"[AUTH] Session active — proceeding with full E2E tests")
        page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-01-intro-authenticated.png"), full_page=True)

        # Flow 2: Onboarding
        page.goto(BASE_URL + "/onboarding", wait_until="networkidle", timeout=15000)
        page.wait_for_timeout(2000)
        page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-02-onboarding.png"), full_page=True)
        body_text = page.inner_text("body")[:500] if page.query_selector("body") else ""
        results.append({
            "path": "/onboarding", "status": "OK", "final_url": page.url,
            "screenshot": "auth-02-onboarding.png",
            "snippet": body_text[:200]
        })

        # Flow 3: Dashboard pages
        dashboard_pages = [
            ("/generate", "auth-03-generate.png"),
            ("/crm/dashboard", "auth-03-crm-dashboard.png"),
            ("/ai-automation", "auth-03-ai-automation.png"),
            ("/info-keyword", "auth-03-info-keyword.png"),
            ("/insuwiki-intro", "auth-03-insuwiki-intro.png"),
            ("/settings", "auth-03-settings.png"),
            ("/contents", "auth-03-contents.png"),
        ]
        for path, ss_name in dashboard_pages:
            errors_before = len(all_console_errors)
            try:
                page.goto(BASE_URL + path, wait_until="networkidle", timeout=15000)
                page.wait_for_timeout(2000)
                page.screenshot(path=os.path.join(SCREENSHOT_DIR, ss_name), full_page=True)
                new_errors = all_console_errors[errors_before:]
                body_text = page.inner_text("body")[:500] if page.query_selector("body") else ""
                results.append({
                    "path": path, "screenshot": ss_name, "status": "OK",
                    "final_url": page.url,
                    "redirected": "/login" in page.url,
                    "console_errors": len(new_errors),
                    "error_details": [e["text"][:200] for e in new_errors],
                    "snippet": body_text[:200]
                })
            except Exception as e:
                results.append({"path": path, "screenshot": ss_name, "status": "FAIL", "error": str(e)[:300]})

        # Flow 4: CRM pages
        crm_pages = [
            ("/crm/customers", "auth-04-crm-customers.png"),
            ("/crm/pipeline", "auth-04-crm-pipeline.png"),
            ("/crm/messenger", "auth-04-crm-messenger.png"),
        ]
        for path, ss_name in crm_pages:
            errors_before = len(all_console_errors)
            try:
                page.goto(BASE_URL + path, wait_until="networkidle", timeout=15000)
                page.wait_for_timeout(2000)
                page.screenshot(path=os.path.join(SCREENSHOT_DIR, ss_name), full_page=True)
                new_errors = all_console_errors[errors_before:]
                body_text = page.inner_text("body")[:500] if page.query_selector("body") else ""
                results.append({
                    "path": path, "screenshot": ss_name, "status": "OK",
                    "final_url": page.url,
                    "redirected": "/login" in page.url,
                    "console_errors": len(new_errors),
                    "has_content": len(body_text) > 50,
                    "snippet": body_text[:200]
                })
            except Exception as e:
                results.append({"path": path, "screenshot": ss_name, "status": "FAIL", "error": str(e)[:300]})

        # Flow 5: Premium/locked features
        premium_pages = ["/ai-onestop", "/ai-automation", "/info-keyword"]
        for pp in premium_pages:
            try:
                page.goto(BASE_URL + pp, wait_until="networkidle", timeout=15000)
                page.wait_for_timeout(2000)
                ss_name = f"auth-05-locked-{pp.replace('/', '-').strip('-')}.png"
                page.screenshot(path=os.path.join(SCREENSHOT_DIR, ss_name), full_page=True)
                body_html = page.content()
                body_text = page.inner_text("body")[:500] if page.query_selector("body") else ""
                has_lock = "Lock" in body_html or "locked" in body_html.lower() or "잠금" in body_html
                has_upgrade = "업그레이드" in body_html or "프리미엄" in body_html or "플랜" in body_html or "Premium" in body_html
                has_blur = "blur" in body_html
                results.append({
                    "path": pp, "check": "premium_lock", "screenshot": ss_name,
                    "status": "OK", "final_url": page.url,
                    "redirected": "/login" in page.url,
                    "has_lock_indicator": has_lock,
                    "has_upgrade_cta": has_upgrade,
                    "has_blur_effect": has_blur,
                    "snippet": body_text[:300]
                })
            except Exception as e:
                results.append({"path": pp, "check": "premium_lock", "status": "FAIL", "error": str(e)[:300]})

    else:
        print(f"[AUTH] Not authenticated — running unauthenticated analysis")

        # Analyze /login page in detail
        page.goto(BASE_URL + "/login", wait_until="networkidle", timeout=15000)
        page.wait_for_timeout(2000)
        page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-00-login-page.png"), full_page=True)
        body_text = page.inner_text("body")[:1000] if page.query_selector("body") else ""
        body_html = page.content()

        # Check login form structure
        has_email_input = bool(page.query_selector('input[type="email"]'))
        has_password_input = bool(page.query_selector('input[type="password"]'))
        has_submit_btn = bool(page.query_selector('button[type="submit"]'))
        has_google_oauth = "google" in body_html.lower() or "Google" in body_html
        has_kakao_oauth = "kakao" in body_html.lower() or "카카오" in body_html

        results.append({
            "path": "/login", "check": "login_page_structure",
            "status": "OK — UNAUTHENTICATED",
            "screenshot": "auth-00-login-page.png",
            "has_email_input": has_email_input,
            "has_password_input": has_password_input,
            "has_submit_button": has_submit_btn,
            "has_google_oauth": has_google_oauth,
            "has_kakao_oauth": has_kakao_oauth,
            "snippet": body_text[:300]
        })

        # Check all protected routes redirect properly
        protected_routes = [
            "/intro", "/onboarding", "/generate",
            "/crm/dashboard", "/crm/customers", "/crm/pipeline", "/crm/messenger",
            "/ai-automation", "/ai-onestop", "/info-keyword",
            "/insuwiki-intro", "/settings", "/contents"
        ]
        for route in protected_routes:
            try:
                page.goto(BASE_URL + route, wait_until="networkidle", timeout=10000)
                page.wait_for_timeout(1000)
                final_url = page.url
                redirected_to_login = "/login" in final_url
                results.append({
                    "path": route,
                    "check": "protected_route_redirect",
                    "status": "PASS" if redirected_to_login else "FAIL — not redirected",
                    "final_url": final_url,
                    "redirected_to_login": redirected_to_login
                })
            except Exception as e:
                results.append({"path": route, "check": "protected_route_redirect", "status": "ERROR", "error": str(e)[:200]})

    context.close()

    # ===== MOBILE CONTEXT =====
    mobile_context = browser.new_context(viewport={"width": 375, "height": 812})
    mobile_page = mobile_context.new_page()
    mobile_page.on("console", lambda msg: all_console_errors.append({
        "type": msg.type, "text": msg.text, "url": mobile_page.url
    }) if msg.type == "error" else None)

    # Inject session on mobile if available
    if login_success and session_data and auth_method and "REST" in auth_method:
        mobile_page.goto(BASE_URL + "/login", wait_until="networkidle", timeout=15000)
        storage_key = "sb-zayhfjuwviporbzokudr-auth-token"
        storage_value = json.dumps({
            "access_token": session_data.get("access_token"),
            "refresh_token": session_data.get("refresh_token"),
            "token_type": "bearer",
            "expires_in": session_data.get("expires_in", 3600),
            "expires_at": session_data.get("expires_at"),
            "user": session_data.get("user"),
        })
        mobile_page.evaluate(f'window.localStorage.setItem("{storage_key}", JSON.stringify({storage_value}))')
        mobile_page.wait_for_timeout(500)
    elif login_success and auth_method and "UI" in auth_method:
        # Re-login on mobile page context
        pass

    try:
        # Check /login mobile responsiveness first
        mobile_page.goto(BASE_URL + "/login", wait_until="networkidle", timeout=15000)
        mobile_page.wait_for_timeout(1500)
        mobile_page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-06-mobile-login.png"), full_page=False)
        login_body = mobile_page.inner_text("body")[:300] if mobile_page.query_selector("body") else ""
        results.append({
            "path": "/login (mobile 375px)", "check": "mobile_login_page",
            "status": "OK", "screenshot": "auth-06-mobile-login.png",
            "snippet": login_body[:200]
        })

        # Navigate to /intro
        mobile_page.goto(BASE_URL + "/intro", wait_until="networkidle", timeout=15000)
        mobile_page.wait_for_timeout(3000)
        final_url = mobile_page.url

        # Check for mobile bottom nav elements
        bottom_nav = mobile_page.query_selector("nav.md\\:hidden, nav[class*='bottom'], nav[class*='fixed']")
        # Also check generic nav elements
        all_navs = mobile_page.query_selector_all("nav")
        nav_info = []
        for nav in all_navs:
            cls = nav.get_attribute("class") or ""
            nav_info.append(cls[:100])

        mobile_page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-06-mobile-intro.png"), full_page=False)
        results.append({
            "path": "/intro (mobile 375px)", "check": "mobile_responsive",
            "mobile_bottom_nav_found": bottom_nav is not None,
            "all_nav_classes": nav_info,
            "status": "OK",
            "final_url": final_url,
            "redirected_to_login": "/login" in final_url
        })

        # Mobile /generate
        mobile_page.goto(BASE_URL + "/generate", wait_until="networkidle", timeout=15000)
        mobile_page.wait_for_timeout(2000)
        bottom_nav2 = mobile_page.query_selector("nav.md\\:hidden, nav[class*='bottom'], nav[class*='fixed']")
        all_navs2 = mobile_page.query_selector_all("nav")
        nav_info2 = []
        for nav in all_navs2:
            cls = nav.get_attribute("class") or ""
            nav_info2.append(cls[:100])
        mobile_page.screenshot(path=os.path.join(SCREENSHOT_DIR, "auth-06-mobile-generate.png"), full_page=False)
        results.append({
            "path": "/generate (mobile 375px)", "check": "mobile_responsive",
            "mobile_bottom_nav_found": bottom_nav2 is not None,
            "all_nav_classes": nav_info2,
            "status": "OK",
            "final_url": mobile_page.url,
            "redirected_to_login": "/login" in mobile_page.url
        })
    except Exception as e:
        results.append({"path": "mobile", "status": "FAIL", "error": str(e)[:300]})

    mobile_context.close()
    browser.close()

# Save results
output = {
    "login_success": login_success,
    "auth_method": auth_method,
    "results": results,
    "total_console_errors": len(all_console_errors),
    "console_errors_detail": [
        {"type": e["type"], "text": e["text"][:200], "url": e["url"]}
        for e in all_console_errors[:50]
    ]
}
with open(os.path.join(SCREENSHOT_DIR, "results_authenticated.json"), "w") as f:
    json.dump(output, f, indent=2, ensure_ascii=False)

print(json.dumps(output, indent=2, ensure_ascii=False))
