import asyncio
from playwright.async_api import async_playwright
import json

BROWSER_ARGS = [
    '--no-sandbox',
    '--disable-setuid-sandbox',
    '--disable-dev-shm-usage',
    '--host-resolver-rules=MAP 100.76.130.39 127.0.0.1',
]

async def capture_dashboard():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True, args=BROWSER_ARGS)
        context = await browser.new_context(viewport={'width': 1920, 'height': 1080})
        page = await context.new_page()

        # 대시보드 접속
        await page.goto('http://100.76.130.39:8000/dashboard/', timeout=30000, wait_until='domcontentloaded')
        await page.wait_for_timeout(3000)
        print(f"Page title: {await page.title()}")

        # 초기 스크린샷 (디버그용)
        await page.screenshot(path='/home/jay/workspace/memory/reports/task-1912-initial.png', full_page=True)
        print("Initial screenshot saved.")

        # 탭 목록 확인
        tabs = await page.query_selector_all('button')
        print(f"Found {len(tabs)} buttons:")
        for tab in tabs:
            txt = await tab.text_content()
            if txt and txt.strip():
                print(f"  Button: '{txt.strip()[:40]}'")

        # 조직뷰 탭 클릭
        org_tab = page.get_by_text('조직뷰')
        count = await org_tab.count()
        print(f"'조직뷰' tab found: {count}")

        if count > 0:
            await org_tab.first.click()
            await page.wait_for_timeout(3000)
            print("Clicked '조직뷰' tab.")
        else:
            print("WARNING: '조직뷰' tab not found by text. Trying alternatives...")
            # aria-label이나 data-tab 속성으로 시도
            alt = page.locator('[data-tab="org"], [aria-label="조직뷰"]')
            if await alt.count() > 0:
                await alt.first.click()
                await page.wait_for_timeout(2000)

        # 전체 스크린샷
        await page.screenshot(path='/home/jay/workspace/memory/reports/task-1912-org-view-full.png', full_page=True)
        print("Full org-view screenshot saved: task-1912-org-view-full.png")

        # StatusDot 요소들 찾기 (bg-emerald, bg-amber, bg-slate, bg-violet 클래스)
        dot_info = await page.evaluate('''() => {
            const results = [];
            const els = document.querySelectorAll('[class]');
            els.forEach(el => {
                const c = el.className || '';
                if (typeof c === 'string' && (
                    c.includes('bg-emerald') ||
                    c.includes('bg-amber') ||
                    c.includes('bg-slate') ||
                    c.includes('bg-violet') ||
                    c.includes('bg-red')
                ) && c.includes('rounded-full')) {
                    // 상위 컨텍스트 - 이름/역할 파악
                    const cardEl = el.closest('[class*="card"], [class*="Card"], [class*="border"], [class*="rounded-lg"]');
                    const nameEl = el.closest('[class*="gap"]');
                    results.push({
                        classes: c.substring(0, 120),
                        cardText: cardEl ? cardEl.textContent.trim().substring(0, 100) : 'N/A',
                        siblingText: nameEl ? nameEl.textContent.trim().substring(0, 80) : 'N/A',
                    });
                }
            });
            return results;
        }''')

        # 팀 카드 섹션 스크린샷
        team_section = page.locator('[class*="grid"], [class*="team"], [class*="org"]').first
        if await team_section.count() > 0:
            await team_section.screenshot(path='/home/jay/workspace/memory/reports/task-1912-team-details.png')
        else:
            await page.screenshot(
                path='/home/jay/workspace/memory/reports/task-1912-team-details.png',
                full_page=True
            )
        print("Team details screenshot saved: task-1912-team-details.png")

        await browser.close()

        # 결과 출력
        print(f"\n=== StatusDot 결과: {len(dot_info)}개 발견 ===")

        # 색상별 분류
        color_map = {
            'bg-emerald': 'working (초록)',
            'bg-amber': 'standby/waiting (노랑)',
            'bg-slate': 'idle (회색)',
            'bg-violet': 'borrowed (보라)',
            'bg-red': 'error/unknown (빨강)',
        }

        color_counts = {}
        for d in dot_info:
            for color_key, label in color_map.items():
                if color_key in d['classes']:
                    color_counts[label] = color_counts.get(label, 0) + 1
                    print(f"  [{label}] context: {d['siblingText'][:70]}")
                    break

        print(f"\n=== 색상별 집계 ===")
        for label, cnt in color_counts.items():
            print(f"  {label}: {cnt}개")

        return dot_info

asyncio.run(capture_dashboard())
