#!/usr/bin/env python3
"""
HTML 파일 업데이트 스크립트
각 사이트의 디자인 분석 정보를 HTML에 추가합니다.
"""

import os
import re

BASE_DIR = "/var/www/tkim.planitai.co.jp/blog/20260130-make-design-adv"

# 사이트별 디자인 정보
SITE_INFO = {
    "001": {
        "name": "Apple",
        "colors": [
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(247, 247, 247)", "hex": "#F7F7F7", "name": "라이트 그레이"},
            {"color": "rgb(192, 0, 20)", "hex": "#C00014", "name": "애플 레드"},
            {"color": "rgb(82, 82, 82)", "hex": "#525252", "name": "다크 그레이"},
        ],
        "features": [
            "<strong>미니멀리즘:</strong> 깔끔하고 간결한 디자인으로 제품에 집중",
            "<strong>화이트 스페이스:</strong> 넉넉한 여백으로 시각적 안정감 제공",
            "<strong>타이포그래피:</strong> San Francisco 폰트 계열(-apple-system)로 일관된 브랜드 아이덴티티",
            "<strong>고품질 이미지:</strong> 제품 사진을 중심으로 한 시각적 스토리텔링",
            "<strong>부드러운 애니메이션:</strong> 스크롤과 호버 시 자연스러운 트랜지션",
            "<strong>명확한 계층 구조:</strong> 제품별 섹션이 명확하게 구분됨",
            "<strong>CTA 버튼:</strong> 'Learn more'와 'Buy' 버튼으로 명확한 행동 유도",
        ]
    },
    "002": {
        "name": "Stripe",
        "colors": [
            {"color": "rgb(99, 91, 255)", "hex": "#635BFF", "name": "스트라이프 퍼플"},
            {"color": "rgb(0, 214, 209)", "hex": "#00D6D1", "name": "시안"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(10, 37, 64)", "hex": "#0A2540", "name": "네이비"},
            {"color": "rgb(247, 250, 252)", "hex": "#F7FAFC", "name": "라이트 그레이"},
        ],
        "features": [
            "<strong>그라데이션 활용:</strong> 브랜드 아이덴티티를 강화하는 보라색 그라데이션",
            "<strong>대담한 타이포그래피:</strong> 큰 제목으로 메시지 강조",
            "<strong>일러스트레이션:</strong> 커스텀 일러스트로 서비스 설명",
            "<strong>애니메이션:</strong> 스크롤에 반응하는 인터랙티브 요소",
            "<strong>명확한 정보 구조:</strong> 개발자 친화적인 문서화",
            "<strong>카드 레이아웃:</strong> 정돈된 그리드 시스템으로 정보 구성",
        ]
    },
    "003": {
        "name": "Linear",
        "colors": [
            {"color": "rgb(88, 76, 255)", "hex": "#584CFF", "name": "리니어 퍼플"},
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(28, 28, 30)", "hex": "#1C1C1E", "name": "다크 배경"},
            {"color": "rgb(142, 142, 147)", "hex": "#8E8E93", "name": "그레이"},
        ],
        "features": [
            "<strong>다크 모드:</strong> 세련된 다크 테마로 프로페셔널한 느낌",
            "<strong>미니멀 UI:</strong> 불필요한 요소를 제거한 깔끔한 인터페이스",
            "<strong>퍼플 액센트:</strong> 브랜드 컬러를 효과적으로 활용",
            "<strong>타이포그래피:</strong> 우아한 세리프와 산세리프 조합",
            "<strong>애니메이션:</strong> 부드럽고 의미있는 모션 디자인",
            "<strong>그리드 시스템:</strong> 정확한 정렬과 간격",
        ]
    },
    "004": {
        "name": "Vercel",
        "colors": [
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(235, 235, 235)", "hex": "#EBEBEB", "name": "라이트 그레이"},
            {"color": "rgb(102, 102, 102)", "hex": "#666666", "name": "그레이"},
            {"color": "rgb(23, 23, 23)", "hex": "#171717", "name": "다크 배경"},
        ],
        "features": [
            "<strong>모노크롬:</strong> 블랙과 화이트 중심의 심플한 컬러 스킴",
            "<strong>그리드 레이아웃:</strong> 정돈된 그리드 시스템",
            "<strong>타이포그래피:</strong> Inter 폰트로 깔끔한 가독성",
            "<strong>다크 모드:</strong> 개발자 친화적인 다크 테마",
            "<strong>애니메이션:</strong> 미세한 호버 효과와 트랜지션",
            "<strong>명확한 위계:</strong> 크기와 굵기로 정보 계층 구분",
        ]
    },
    "005": {
        "name": "Figma",
        "colors": [
            {"color": "rgb(255, 114, 98)", "hex": "#FF7262", "name": "코랄 레드"},
            {"color": "rgb(162, 89, 255)", "hex": "#A259FF", "name": "퍼플"},
            {"color": "rgb(26, 188, 254)", "hex": "#1ABCFE", "name": "블루"},
            {"color": "rgb(10, 207, 131)", "hex": "#0ACF83", "name": "그린"},
            {"color": "rgb(255, 196, 0)", "hex": "#FFC400", "name": "옐로우"},
        ],
        "features": [
            "<strong>다채로운 컬러:</strong> 밝고 활기찬 브랜드 컬러 팔레트",
            "<strong>일러스트레이션:</strong> 3D 그래픽과 커스텀 일러스트",
            "<strong>화이트 스페이스:</strong> 여유로운 레이아웃",
            "<strong>타이포그래피:</strong> 명확한 계층 구조의 텍스트",
            "<strong>인터랙션:</strong> 사용자 참여를 유도하는 동적 요소",
            "<strong>반응형 디자인:</strong> 모든 화면 크기에 최적화",
        ]
    },
    "006": {
        "name": "Notion",
        "colors": [
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(55, 53, 47)", "hex": "#37352F", "name": "다크 텍스트"},
            {"color": "rgb(247, 246, 243)", "hex": "#F7F6F3", "name": "베이지 배경"},
            {"color": "rgb(235, 236, 237)", "hex": "#EBECED", "name": "라이트 그레이"},
        ],
        "features": [
            "<strong>심플함:</strong> 직관적이고 이해하기 쉬운 디자인",
            "<strong>파스텔 컬러:</strong> 부드러운 파스텔 톤의 배색",
            "<strong>일러스트레이션:</strong> 친근한 느낌의 커스텀 일러스트",
            "<strong>타이포그래피:</strong> 가독성 높은 폰트 선택",
            "<strong>라이트/다크 모드:</strong> 사용자 선택 가능한 테마",
            "<strong>모듈형 레이아웃:</strong> 블록 기반 콘텐츠 구성",
        ]
    },
    "007": {
        "name": "Webflow",
        "colors": [
            {"color": "rgb(66, 95, 254)", "hex": "#425FFE", "name": "웹플로우 블루"},
            {"color": "rgb(255, 82, 111)", "hex": "#FF526F", "name": "핑크"},
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(242, 242, 247)", "hex": "#F2F2F7", "name": "라이트 그레이"},
        ],
        "features": [
            "<strong>그라데이션:</strong> 대담한 컬러 그라데이션",
            "<strong>3D 요소:</strong> 입체감 있는 디자인 요소",
            "<strong>타이포그래피:</strong> 큰 헤딩과 명확한 계층",
            "<strong>애니메이션:</strong> 스크롤 기반 패럴랙스 효과",
            "<strong>레이아웃:</strong> 복잡하지만 정돈된 그리드",
            "<strong>비주얼 중심:</strong> 강렬한 이미지와 그래픽 활용",
        ]
    },
    "008": {
        "name": "Framer",
        "colors": [
            {"color": "rgb(10, 10, 10)", "hex": "#0A0A0A", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(0, 153, 255)", "hex": "#0099FF", "name": "프레이머 블루"},
            {"color": "rgb(128, 90, 213)", "hex": "#805AD5", "name": "퍼플"},
            {"color": "rgb(242, 242, 242)", "hex": "#F2F2F2", "name": "라이트 그레이"},
        ],
        "features": [
            "<strong>인터랙티브:</strong> 고도로 인터랙티브한 UI 요소",
            "<strong>애니메이션:</strong> 유려한 모션 디자인",
            "<strong>다크 모드:</strong> 세련된 다크 테마",
            "<strong>타이포그래피:</strong> 모던한 산세리프 폰트",
            "<strong>그라데이션:</strong> 미묘한 컬러 그라데이션",
            "<strong>프로토타이핑 도구:</strong> 디자인과 프로토타이핑의 결합",
        ]
    },
    "009": {
        "name": "Airbnb",
        "colors": [
            {"color": "rgb(255, 90, 95)", "hex": "#FF5A5F", "name": "에어비앤비 핑크"},
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(113, 113, 113)", "hex": "#717171", "name": "그레이"},
            {"color": "rgb(247, 247, 247)", "hex": "#F7F7F7", "name": "라이트 그레이"},
        ],
        "features": [
            "<strong>사진 중심:</strong> 고품질 숙소 이미지가 주요 콘텐츠",
            "<strong>핑크 브랜드 컬러:</strong> Airbnb만의 독특한 핑크색",
            "<strong>카드 레이아웃:</strong> 그리드 기반 카드 디자인",
            "<strong>타이포그래피:</strong> Cereal 커스텀 폰트",
            "<strong>검색 UI:</strong> 직관적인 검색 인터페이스",
            "<strong>반응형 그리드:</strong> 화면 크기에 따라 최적화된 레이아웃",
        ]
    },
    "010": {
        "name": "Tesla",
        "colors": [
            {"color": "rgb(0, 0, 0)", "hex": "#000000", "name": "블랙"},
            {"color": "rgb(255, 255, 255)", "hex": "#FFFFFF", "name": "화이트"},
            {"color": "rgb(23, 26, 32)", "hex": "#171A20", "name": "다크 배경"},
            {"color": "rgb(243, 243, 243)", "hex": "#F3F3F3", "name": "라이트 그레이"},
            {"color": "rgb(51, 51, 51)", "hex": "#333333", "name": "그레이"},
        ],
        "features": [
            "<strong>풀스크린 이미지:</strong> 압도적인 제품 비주얼",
            "<strong>미니멀 UI:</strong> 간결한 네비게이션과 CTA",
            "<strong>타이포그래피:</strong> 고딕 계열의 심플한 폰트",
            "<strong>블랙 & 화이트:</strong> 모던한 모노톤 배색",
            "<strong>비디오 콘텐츠:</strong> 동영상을 활용한 제품 소개",
            "<strong>스크롤 UX:</strong> 풀페이지 스크롤로 제품별 섹션 구분",
        ]
    },
}

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'

    for color_info in colors:
        border = ' border: 1px solid #e5e7eb;' if 'white' in color_info['name'].lower() or 'gray' in color_info['name'].lower() and color_info['hex'].startswith('#F') else ''
        html += f'''                        <div style="text-align: center;">
                            <div style="background: {color_info['color']}; height: 60px; border-radius: 8px; margin-bottom: 8px;{border}"></div>
                            <div style="font-size: 12px; color: #6b7280;">{color_info['name']}<br>{color_info['hex']}</div>
                        </div>\n'''

    html += '                    </div>'
    return html

def generate_design_features_html(features):
    """디자인 특징 HTML 생성"""
    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(file_num, site_info):
    """HTML 파일 업데이트"""
    html_file = os.path.join(BASE_DIR, f"{file_num}.html")

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

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

        # 색상 팔레트와 디자인 특징 HTML 생성
        color_palette_html = generate_color_palette_html(site_info['colors'])
        design_features_html = generate_design_features_html(site_info['features'])

        # 새 섹션 생성
        new_section = f'''            <div class="section">
                <h2 class="section-title">실제 디자인 분석</h2>
                <div class="section-content">
                    <img src="screenshots/{file_num}.png" alt="{site_info['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>

            '''

        # 기존에 "실제 디자인 분석" 섹션이 있는지 확인
        if '실제 디자인 분석' in content:
            # 기존 섹션 제거
            pattern = r'            <div class="section">.*?<h2 class="section-title">실제 디자인 분석</h2>.*?</div>\s*</div>\s*\n\s*\n'
            content = re.sub(pattern, '', content, flags=re.DOTALL)

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

        if tag_section_pos == -1:
            print(f"✗ 학습 태그 섹션을 찾을 수 없음: {file_num}")
            return False

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

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

        print(f"✓ {file_num}. {site_info['name']} HTML 업데이트 완료")
        return True

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

def main():
    """메인 실행 함수"""
    print("=" * 60)
    print("HTML 파일 업데이트 시작")
    print("=" * 60)

    success_count = 0
    for file_num, site_info in SITE_INFO.items():
        if update_html_file(file_num, site_info):
            success_count += 1

    print("\n" + "=" * 60)
    print(f"완료: {success_count}/{len(SITE_INFO)} 파일 업데이트됨")
    print("=" * 60)

    print("\n주의: 실제 스크린샷은 수동으로 screenshots/ 폴더에 추가해야 합니다.")
    print("스크린샷 파일명: 001.png ~ 010.png")

if __name__ == "__main__":
    main()
