#!/usr/bin/env python3
"""
웹사이트 분석 및 HTML 업데이트 스크립트
Playwright를 사용하여 웹사이트를 방문하고 스크린샷을 캡처한 후 HTML 파일을 업데이트합니다.
"""

import asyncio
import os
import json
import re
from pathlib import Path
from playwright.async_api import async_playwright

# 작업 디렉토리
BASE_DIR = Path("/var/www/tkim.planitai.co.jp/blog/20260130-make-design-adv")
SCREENSHOTS_DIR = BASE_DIR / "screenshots"

# 분석 대상 사이트 (011-020)
SITES = [
    {"num": "011", "name": "Spotify", "url": "https://www.spotify.com/"},
    {"num": "012", "name": "Netflix", "url": "https://www.netflix.com/"},
    {"num": "013", "name": "Adobe", "url": "https://www.adobe.com/"},
    {"num": "014", "name": "Microsoft", "url": "https://www.microsoft.com/en-us/"},
    {"num": "015", "name": "Google", "url": "https://about.google/"},
    {"num": "016", "name": "Shopify", "url": "https://www.shopify.com/"},
    {"num": "017", "name": "Salesforce", "url": "https://www.salesforce.com/"},
    {"num": "018", "name": "Slack", "url": "https://slack.com/"},
    {"num": "019", "name": "Discord", "url": "https://discord.com/"},
    {"num": "020", "name": "Dropbox", "url": "https://www.dropbox.com/"},
]


async def capture_screenshot(page, site):
    """웹사이트 스크린샷 캡처"""
    try:
        print(f"  → {site['name']} 방문 중...")
        await page.goto(site['url'], wait_until='networkidle', timeout=30000)
        await page.wait_for_timeout(2000)  # 추가 로딩 대기

        screenshot_path = SCREENSHOTS_DIR / f"{site['num']}.png"
        print(f"  → 스크린샷 캡처 중: {screenshot_path}")
        await page.screenshot(path=str(screenshot_path), full_page=True)

        return True
    except Exception as e:
        print(f"  ✗ 오류 발생: {str(e)}")
        return False


async def analyze_design(page, site):
    """웹사이트 디자인 요소 분석"""
    try:
        # 색상 추출
        colors = await page.evaluate("""
            () => {
                const colors = new Set();
                const elements = document.querySelectorAll('*');

                elements.forEach(el => {
                    const style = window.getComputedStyle(el);
                    const bgColor = style.backgroundColor;
                    const color = style.color;

                    if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)') {
                        colors.add(bgColor);
                    }
                    if (color) {
                        colors.add(color);
                    }
                });

                return Array.from(colors).slice(0, 10);
            }
        """)

        # 폰트 추출
        fonts = await page.evaluate("""
            () => {
                const fonts = new Set();
                const elements = document.querySelectorAll('h1, h2, h3, p, button, a');

                elements.forEach(el => {
                    const style = window.getComputedStyle(el);
                    const fontFamily = style.fontFamily;
                    if (fontFamily) {
                        fonts.add(fontFamily);
                    }
                });

                return Array.from(fonts).slice(0, 5);
            }
        """)

        # 레이아웃 정보
        layout = await page.evaluate("""
            () => {
                const body = document.body;
                const style = window.getComputedStyle(body);
                return {
                    maxWidth: style.maxWidth,
                    padding: style.padding,
                    margin: style.margin
                };
            }
        """)

        return {
            "colors": colors,
            "fonts": fonts,
            "layout": layout
        }
    except Exception as e:
        print(f"  ✗ 디자인 분석 오류: {str(e)}")
        return None


def rgb_to_hex(rgb_str):
    """RGB 문자열을 HEX로 변환"""
    try:
        # rgba(255, 255, 255, 1) 또는 rgb(255, 255, 255) 형식 파싱
        match = re.search(r'rgba?\((\d+),\s*(\d+),\s*(\d+)', rgb_str)
        if match:
            r, g, b = match.groups()
            return f"#{int(r):02x}{int(g):02x}{int(b):02x}"
        return rgb_str
    except:
        return rgb_str


def update_html_file(site, analysis):
    """HTML 파일에 실제 디자인 분석 섹션 추가"""
    html_path = BASE_DIR / f"{site['num']}.html"

    try:
        with open(html_path, 'r', encoding='utf-8') as f:
            content = f.read()

        # "학습 태그" 섹션 바로 앞에 새로운 섹션 추가
        new_section = f"""
            <div class="section">
                <h2 class="section-title">실제 디자인 분석</h2>
                <div class="section-content">
                    <div style="margin-bottom: 24px;">
                        <img src="screenshots/{site['num']}.png" alt="{site['name']} 스크린샷" style="width: 100%; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                    </div>

                    <h3 style="margin-top: 24px; margin-bottom: 12px; font-size: 18px; color: #374151;">주요 색상 팔레트</h3>
                    <div style="display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 24px;">
"""

        # 색상 팔레트 추가 (상위 5개)
        if analysis and analysis.get('colors'):
            for color in analysis['colors'][:5]:
                hex_color = rgb_to_hex(color)
                new_section += f"""                        <div style="display: flex; flex-direction: column; align-items: center;">
                            <div style="width: 80px; height: 80px; background: {color}; border-radius: 8px; border: 1px solid #e5e7eb;"></div>
                            <code style="margin-top: 8px; font-size: 12px; color: #6b7280;">{hex_color}</code>
                        </div>
"""

        new_section += """                    </div>

                    <h3 style="margin-top: 24px; margin-bottom: 12px; font-size: 18px; color: #374151;">사용된 폰트</h3>
                    <div style="background: #f9fafb; padding: 16px; border-radius: 8px; margin-bottom: 24px;">
"""

        # 폰트 정보 추가
        if analysis and analysis.get('fonts'):
            for font in analysis['fonts']:
                new_section += f"""                        <div style="margin-bottom: 8px; color: #4b5563; font-family: {font};">
                            <code style="background: white; padding: 4px 8px; border-radius: 4px; font-size: 13px;">{font}</code>
                        </div>
"""

        new_section += """                    </div>

                    <h3 style="margin-top: 24px; margin-bottom: 12px; font-size: 18px; color: #374151;">디자인 특징</h3>
                    <ul style="padding-left: 20px; color: #4b5563; line-height: 1.8;">
                        <li>반응형 레이아웃으로 다양한 디바이스 지원</li>
                        <li>일관된 브랜드 아이덴티티와 색상 사용</li>
                        <li>명확한 타이포그래피 계층 구조</li>
                        <li>사용자 친화적인 네비게이션 구조</li>
                        <li>효과적인 시각적 계층과 여백 활용</li>
                    </ul>
                </div>
            </div>

"""

        # "학습 태그" 섹션 찾기
        tag_section_pattern = r'(<div class="section">\s*<h2 class="section-title">학습 태그</h2>)'

        if re.search(tag_section_pattern, content):
            # "학습 태그" 섹션 바로 앞에 삽입
            updated_content = re.sub(tag_section_pattern, new_section + r'\1', content)

            with open(html_path, 'w', encoding='utf-8') as f:
                f.write(updated_content)

            print(f"  ✓ HTML 파일 업데이트 완료: {html_path}")
            return True
        else:
            print(f"  ✗ '학습 태그' 섹션을 찾을 수 없습니다.")
            return False

    except Exception as e:
        print(f"  ✗ HTML 업데이트 오류: {str(e)}")
        return False


async def process_site(page, site):
    """개별 사이트 처리"""
    print(f"\n[{site['num']}] {site['name']} 처리 중...")

    # 스크린샷 캡처
    screenshot_success = await capture_screenshot(page, site)

    if not screenshot_success:
        print(f"  ✗ {site['name']} 스크린샷 실패")
        return False

    # 디자인 분석
    analysis = await analyze_design(page, site)

    # HTML 파일 업데이트
    update_success = update_html_file(site, analysis)

    if update_success:
        print(f"  ✓ {site['name']} 완료")
        return True
    else:
        print(f"  ✗ {site['name']} HTML 업데이트 실패")
        return False


async def main():
    """메인 실행 함수"""
    print("=" * 60)
    print("웹사이트 디자인 분석 스크립트 시작")
    print("=" * 60)

    # screenshots 디렉토리 확인
    SCREENSHOTS_DIR.mkdir(exist_ok=True)
    print(f"Screenshots 디렉토리: {SCREENSHOTS_DIR}")

    async with async_playwright() as p:
        # 브라우저 실행
        print("\n브라우저 시작 중...")
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        )
        page = await context.new_page()

        # 각 사이트 처리
        results = []
        for site in SITES:
            try:
                success = await process_site(page, site)
                results.append({"site": site['name'], "success": success})
            except Exception as e:
                print(f"  ✗ {site['name']} 처리 중 오류: {str(e)}")
                results.append({"site": site['name'], "success": False, "error": str(e)})

        # 브라우저 종료
        await browser.close()

    # 결과 요약
    print("\n" + "=" * 60)
    print("처리 결과 요약")
    print("=" * 60)

    success_count = sum(1 for r in results if r['success'])
    total_count = len(results)

    for result in results:
        status = "✓" if result['success'] else "✗"
        print(f"  {status} {result['site']}")

    print(f"\n완료: {success_count}/{total_count}")
    print("=" * 60)


if __name__ == "__main__":
    asyncio.run(main())
