#!/usr/bin/env python3
"""
웹사이트 디자인 분석 및 HTML 업데이트 스크립트
Playwright MCP를 사용하여 각 사이트를 분석하고 스크린샷을 캡처합니다.
"""

import os
import time
from playwright.sync_api import sync_playwright

# 분석 대상 사이트 (001-010)
SITES = [
    {"num": "001", "name": "Apple", "url": "https://www.apple.com/"},
    {"num": "002", "name": "Stripe", "url": "https://stripe.com/"},
    {"num": "003", "name": "Linear", "url": "https://linear.app/"},
    {"num": "004", "name": "Vercel", "url": "https://vercel.com/"},
    {"num": "005", "name": "Figma", "url": "https://www.figma.com/"},
    {"num": "006", "name": "Notion", "url": "https://www.notion.so/"},
    {"num": "007", "name": "Webflow", "url": "https://webflow.com/"},
    {"num": "008", "name": "Framer", "url": "https://www.framer.com/"},
    {"num": "009", "name": "Airbnb", "url": "https://www.airbnb.com/"},
    {"num": "010", "name": "Tesla", "url": "https://www.tesla.com/"},
]

BASE_DIR = "/var/www/tkim.planitai.co.jp/blog/20260130-make-design-adv"
SCREENSHOTS_DIR = os.path.join(BASE_DIR, "screenshots")

def rgb_to_hex(rgb_str):
    """RGB 문자열을 HEX로 변환"""
    try:
        if rgb_str.startswith('rgb('):
            rgb = rgb_str.replace('rgb(', '').replace(')', '').split(',')
            r, g, b = [int(x.strip()) for x in rgb]
            return f"#{r:02x}{g:02x}{b:02x}".upper()
        elif rgb_str.startswith('rgba('):
            rgba = rgb_str.replace('rgba(', '').replace(')', '').split(',')
            r, g, b = [int(x.strip()) for x in rgba[:3]]
            return f"#{r:02x}{g:02x}{b:02x}".upper()
    except:
        pass
    return rgb_str

def analyze_site(page, site):
    """사이트 분석 및 스크린샷 캡처"""
    print(f"\n분석 중: {site['num']}. {site['name']} ({site['url']})")

    try:
        # 페이지 방문
        page.goto(site['url'], wait_until='networkidle', timeout=30000)
        time.sleep(2)  # 추가 로딩 대기

        # 스크린샷 캡처
        screenshot_path = os.path.join(SCREENSHOTS_DIR, f"{site['num']}.png")
        page.screenshot(path=screenshot_path, full_page=True)
        print(f"✓ 스크린샷 저장: {screenshot_path}")

        # 색상 추출
        colors = page.evaluate("""
            () => {
                const elements = document.querySelectorAll('*');
                const colorSet = new Set();

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

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

                return Array.from(colorSet).slice(0, 15);
            }
        """)

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

                elements.forEach(el => {
                    const styles = window.getComputedStyle(el);
                    fontSet.add(styles.fontFamily);
                });

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

        # 레이아웃 정보 추출
        layout_info = page.evaluate("""
            () => {
                const body = document.body;
                const styles = window.getComputedStyle(body);

                return {
                    backgroundColor: styles.backgroundColor,
                    maxWidth: document.querySelector('main, .container, [class*="container"]')?.offsetWidth || 'N/A',
                    gridGap: styles.gap || styles.gridGap || 'N/A'
                };
            }
        """)

        return {
            'success': True,
            'colors': colors,
            'fonts': fonts,
            'layout': layout_info
        }

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

def generate_color_palette_html(colors):
    """색상 팔레트 HTML 생성"""
    html = '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 12px; margin-bottom: 24px;">\n'

    # 주요 색상 필터링 (투명 제외)
    main_colors = []
    for color in colors[:10]:
        if 'rgba(0, 0, 0, 0)' not in color:
            main_colors.append(color)

    for color in main_colors[:5]:
        hex_color = rgb_to_hex(color)
        border = ' border: 1px solid #e5e7eb;' if 'rgb(255, 255, 255)' in color or 'rgb(247' in color else ''
        html += f'''                        <div style="text-align: center;">
                            <div style="background: {color}; height: 60px; border-radius: 8px; margin-bottom: 8px;{border}"></div>
                            <div style="font-size: 12px; color: #6b7280;">{hex_color}</div>
                        </div>\n'''

    html += '                    </div>'
    return html

def generate_design_features_html(site, analysis):
    """디자인 특징 HTML 생성"""
    features = []

    # 사이트별 특징 정의
    site_features = {
        "Apple": [
            "<strong>미니멀리즘:</strong> 깔끔하고 간결한 디자인으로 제품에 집중",
            "<strong>화이트 스페이스:</strong> 넉넉한 여백으로 시각적 안정감 제공",
            "<strong>타이포그래피:</strong> San Francisco 폰트 계열로 일관된 브랜드 아이덴티티",
            "<strong>고품질 이미지:</strong> 제품 사진을 중심으로 한 시각적 스토리텔링",
            "<strong>부드러운 애니메이션:</strong> 스크롤과 호버 시 자연스러운 트랜지션",
            "<strong>명확한 계층 구조:</strong> 제품별 섹션이 명확하게 구분됨",
        ],
        "Stripe": [
            "<strong>그라데이션 활용:</strong> 브랜드 아이덴티티를 강화하는 보라색 그라데이션",
            "<strong>대담한 타이포그래피:</strong> 큰 제목으로 메시지 강조",
            "<strong>일러스트레이션:</strong> 커스텀 일러스트로 서비스 설명",
            "<strong>애니메이션:</strong> 스크롤에 반응하는 인터랙티브 요소",
            "<strong>명확한 정보 구조:</strong> 개발자 친화적인 문서화",
        ],
        "Linear": [
            "<strong>다크 모드:</strong> 세련된 다크 테마로 프로페셔널한 느낌",
            "<strong>미니멀 UI:</strong> 불필요한 요소를 제거한 깔끔한 인터페이스",
            "<strong>퍼플 액센트:</strong> 브랜드 컬러를 효과적으로 활용",
            "<strong>타이포그래피:</strong> 우아한 세리프와 산세리프 조합",
            "<strong>애니메이션:</strong> 부드럽고 의미있는 모션 디자인",
        ],
        "Vercel": [
            "<strong>모노크롬:</strong> 블랙과 화이트 중심의 심플한 컬러 스킴",
            "<strong>그리드 레이아웃:</strong> 정돈된 그리드 시스템",
            "<strong>타이포그래피:</strong> Inter 폰트로 깔끔한 가독성",
            "<strong>다크 모드:</strong> 개발자 친화적인 다크 테마",
            "<strong>애니메이션:</strong> 미세한 호버 효과와 트랜지션",
        ],
        "Figma": [
            "<strong>다채로운 컬러:</strong> 밝고 활기찬 브랜드 컬러 팔레트",
            "<strong>일러스트레이션:</strong> 3D 그래픽과 커스텀 일러스트",
            "<strong>화이트 스페이스:</strong> 여유로운 레이아웃",
            "<strong>타이포그래피:</strong> 명확한 계층 구조의 텍스트",
            "<strong>인터랙션:</strong> 사용자 참여를 유도하는 동적 요소",
        ],
        "Notion": [
            "<strong>심플함:</strong> 직관적이고 이해하기 쉬운 디자인",
            "<strong>파스텔 컬러:</strong> 부드러운 파스텔 톤의 배색",
            "<strong>일러스트레이션:</strong> 친근한 느낌의 커스텀 일러스트",
            "<strong>타이포그래피:</strong> 가독성 높은 폰트 선택",
            "<strong>라이트/다크 모드:</strong> 사용자 선택 가능한 테마",
        ],
        "Webflow": [
            "<strong>그라데이션:</strong> 대담한 컬러 그라데이션",
            "<strong>3D 요소:</strong> 입체감 있는 디자인 요소",
            "<strong>타이포그래피:</strong> 큰 헤딩과 명확한 계층",
            "<strong>애니메이션:</strong> 스크롤 기반 패럴랙스 효과",
            "<strong>레이아웃:</strong> 복잡하지만 정돈된 그리드",
        ],
        "Framer": [
            "<strong>인터랙티브:</strong> 고도로 인터랙티브한 UI 요소",
            "<strong>애니메이션:</strong> 유려한 모션 디자인",
            "<strong>다크 모드:</strong> 세련된 다크 테마",
            "<strong>타이포그래피:</strong> 모던한 산세리프 폰트",
            "<strong>그라데이션:</strong> 미묘한 컬러 그라데이션",
        ],
        "Airbnb": [
            "<strong>사진 중심:</strong> 고품질 숙소 이미지가 주요 콘텐츠",
            "<strong>핑크 브랜드 컬러:</strong> Airbnb만의 독특한 핑크색",
            "<strong>카드 레이아웃:</strong> 그리드 기반 카드 디자인",
            "<strong>타이포그래피:</strong> Cereal 커스텀 폰트",
            "<strong>검색 UI:</strong> 직관적인 검색 인터페이스",
        ],
        "Tesla": [
            "<strong>풀스크린 이미지:</strong> 압도적인 제품 비주얼",
            "<strong>미니멀 UI:</strong> 간결한 네비게이션과 CTA",
            "<strong>타이포그래피:</strong> 고딕 계열의 심플한 폰트",
            "<strong>블랙 & 화이트:</strong> 모던한 모노톤 배색",
            "<strong>비디오 콘텐츠:</strong> 동영상을 활용한 제품 소개",
        ],
    }

    features = site_features.get(site['name'], [
        "<strong>색상:</strong> 브랜드 아이덴티티를 반영한 컬러 스킴",
        "<strong>레이아웃:</strong> 정돈된 그리드 시스템",
        "<strong>타이포그래피:</strong> 가독성 높은 폰트 선택",
        "<strong>이미지:</strong> 고품질 비주얼 콘텐츠",
    ])

    html = '<ul style="padding-left: 20px; color: #4b5563; line-height: 1.8;">\n'
    for feature in features:
        html += f'                        <li>{feature}</li>\n'
    html += '                    </ul>'

    return html

def update_html_file(site, analysis):
    """HTML 파일 업데이트"""
    html_file = os.path.join(BASE_DIR, f"{site['num']}.html")

    if not os.path.exists(html_file):
        print(f"✗ HTML 파일 없음: {html_file}")
        return

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

        # "학습 태그" 섹션 찾기
        tag_section_start = content.find('<div class="section">\n                <h2 class="section-title">학습 태그</h2>')

        if tag_section_start == -1:
            print(f"✗ 학습 태그 섹션을 찾을 수 없음")
            return

        # 새 섹션 생성
        color_palette_html = generate_color_palette_html(analysis.get('colors', []))
        design_features_html = generate_design_features_html(site, analysis)

        new_section = f'''            <div class="section">
                <h2 class="section-title">실제 디자인 분석</h2>
                <div class="section-content">
                    <img src="screenshots/{site['num']}.png" alt="{site['name']} 웹사이트 스크린샷" style="width: 100%; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">

                    <h3 style="margin-top: 24px; margin-bottom: 12px; font-size: 18px; color: #374151;">주요 색상 팔레트</h3>
                    {color_palette_html}

                    <h3 style="margin-top: 24px; margin-bottom: 12px; font-size: 18px; color: #374151;">디자인 특징</h3>
                    {design_features_html}
                </div>
            </div>

            '''

        # 기존에 "실제 디자인 분석" 섹션이 있는지 확인
        real_analysis_start = content.find('<div class="section">\n                <h2 class="section-title">실제 디자인 분석</h2>')

        if real_analysis_start != -1:
            # 기존 섹션 제거
            real_analysis_end = content.find('            <div class="section">\n                <h2 class="section-title">학습 태그</h2>', real_analysis_start)
            content = content[:real_analysis_start] + content[real_analysis_end:]
            tag_section_start = content.find('<div class="section">\n                <h2 class="section-title">학습 태그</h2>')

        # 새 섹션 삽입
        updated_content = content[:tag_section_start] + new_section + content[tag_section_start:]

        # 파일 저장
        with open(html_file, 'w', encoding='utf-8') as f:
            f.write(updated_content)

        print(f"✓ HTML 업데이트 완료: {html_file}")

    except Exception as e:
        print(f"✗ HTML 업데이트 실패: {str(e)}")

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

    # screenshots 디렉토리 확인
    os.makedirs(SCREENSHOTS_DIR, exist_ok=True)

    with sync_playwright() as p:
        # 브라우저 실행
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        )
        page = context.new_page()

        # 각 사이트 분석
        for site in SITES:
            analysis = analyze_site(page, site)

            if analysis['success']:
                update_html_file(site, analysis)
            else:
                print(f"✗ {site['num']}. {site['name']} 분석 실패: {analysis.get('error', 'Unknown error')}")

            time.sleep(1)  # 서버 부하 방지

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

    print("\n" + "=" * 60)
    print("분석 완료!")
    print("=" * 60)

if __name__ == "__main__":
    main()
