#!/usr/bin/env python3
"""
Convert organizational design HTML slides to PPTX using python-pptx.
This script creates a clean, professional PPTX with proper layouts.
"""
from pptx import Presentation
from pptx.util import Inches, Pt, Emu
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
import os

# Theme colors
THEMES = {
    'theme-dark': {'bg': RGBColor(0x0F, 0x17, 0x2A), 'text': RGBColor(0xF8, 0xFA, 0xFC), 'accent': RGBColor(0x63, 0x66, 0xF1)},
    'theme-light': {'bg': RGBColor(0xF8, 0xFA, 0xFC), 'text': RGBColor(0x0F, 0x17, 0x2A), 'accent': RGBColor(0x4F, 0x46, 0xE5)},
    'theme-accent': {'bg': RGBColor(0x1E, 0x3A, 0x5F), 'text': RGBColor(0xF8, 0xFA, 0xFC), 'accent': RGBColor(0x81, 0x8C, 0xF8)},
    'theme-navy': {'bg': RGBColor(0x0B, 0x12, 0x20), 'text': RGBColor(0xF8, 0xFA, 0xFC), 'accent': RGBColor(0x63, 0x66, 0xF1)},
}

# Slide content extracted from HTML
SLIDES = [
    {
        'theme': 'theme-dark',
        'type': 'title',
        'title': '組織設計',
        'subtitle': '策略、結構與效能的系統性整合',
    },
    {
        'theme': 'theme-light',
        'type': 'agenda',
        'title': '簡報大綱',
        'items': [
            {'num': '01', 'title': '組織設計基礎', 'desc': '定義、目的與核心原則'},
            {'num': '02', 'title': '組織結構類型', 'desc': '機能、事業部、矩陣、網路型'},
            {'num': '03', 'title': '設計驅動因素', 'desc': '策略、規模、技術、環境'},
            {'num': '04', 'title': '權責與協調機制', 'desc': '集權分權、整合性角色、溝通管道'},
            {'num': '05', 'title': '趨勢與個案', 'desc': '敏捷組織、平台化、台灣實踐'},
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'content',
        'title': '什麼是組織設計？',
        'content': [
            '組織設計是一套系統性方法，用來決定組織如何分工、協調與配置資源，以有效達成策略目標。',
            '',
            '• 決定權責歸屬與報告關係',
            '• 設計跨部門協調機制',
            '• 配置人力、預算與技術資源',
            '• 回應外部環境變化與策略需求',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '為什麼組織設計很重要？',
        'content': [
            '• 策略執行力：再好的策略，沒有對的組織結構來承載，最終只是紙上談兵。',
            '• 人才效能：對的結構讓對的人在對的位置，發揮最大戰力。',
            '• 反應速度：扁平、靈活的結構讓組織更快回應市場變化。',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'content',
        'title': '組織設計的演進',
        'content': [
            '• 1900s 古典理論：費堯、韋伯提出官僚體制與管理原則，強調分工與層級',
            '• 1950s 行為學派：馬斯洛、赫茲伯格關注人的動機與非正式組織',
            '• 1980s 權變理論：沒有唯一最佳結構，組織設計必須回應環境與策略',
            '• 2000s 網路與平台：跨組織邊界、生態系協作、虛擬整合',
            '• 2020s+ 敏捷與去中心化：自組織團隊、OKR、敏捷 Scrum、AI 輔助決策',
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'section',
        'title': '組織結構類型',
        'subtitle': '不同結構適用不同情境，關鍵是結構必須服務於策略，而非制約策略。',
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '01 機能型組織',
        'content': [
            '依專業職能分工，是最傳統也最常見的組織結構。',
            '',
            '• 研發、生產、行銷、財務各自獨立',
            '• 專業深度高，規模經濟明顯',
            '• 決策集中，跨部門協調成本高',
            '• 適合：穩定環境、單一產品線',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'content',
        'title': '02 事業部型組織',
        'content': [
            '依產品、地區或客戶劃分獨立事業單位。',
            '',
            '• 各事業部擁有完整機能（研產銷人財）',
            '• 利潤責任明確，回應市場速度快',
            '• 資源重複配置，規模經濟降低',
            '• 適合：多產品線、跨國企業',
            '',
            '⚠️ 常見問題：事業部各自為政、資源搶奪、知識無法共享',
            '✅ 解方：設立共享服務中心、跨事業部委員會',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '03 矩陣型組織',
        'content': [
            '同時以職能與專案/產品雙軸管理，員工有兩個上級。',
            '',
            '• 兼顧專業深度與產品回應速度',
            '• 資源可跨專案共享',
            '• 雙重報告關係造成權責模糊',
            '• 適合：專案導向、技術複雜產業',
            '',
            '矩陣核心矛盾：「誰說了算？」職能主管 vs 專案主管的權力拉鋸',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'content',
        'title': '04 網路型 / 平台型組織',
        'content': [
            '組織核心小、外包多，透過合約與夥伴關係完成價值鏈。',
            '',
            '• 核心能力保留，非核心外包',
            '• 彈性極高，資本投入低',
            '• 品質與供應鏈風險較高',
            '• 適合：新創、時尚、科技服務',
            '',
            '代表案例：Nike、Apple、Zara',
            '品牌與設計保留，製造全面外包',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'table',
        'title': '四種結構比較',
        'headers': ['維度', '機能型', '事業部型', '矩陣型', '網路型'],
        'rows': [
            ['分工基礎', '職能', '產品/地區', '職能×專案', '核心能力'],
            ['決策速度', '慢（集中）', '快（分散）', '中等', '快'],
            ['資源效率', '高', '低', '中等', '高'],
            ['彈性', '低', '中等', '中高', '高'],
            ['協調成本', '高', '低', '極高', '中等'],
            ['適合規模', '中小型', '大型', '大型', '任意'],
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'section',
        'title': '組織設計驅動因素',
        'subtitle': '組織結構不是隨意畫的，它受到四大因素驅動：策略、規模、技術與環境。',
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '策略決定結構',
        'content': [
            'Alfred Chandler 的經典命題：「結構跟隨策略」。組織的結構必須支撐其策略方向。',
            '',
            '• 成本領導 → 集中化、標準化、規模經濟',
            '• 差異化 → 分散化、跨部門協作、創新彈性',
            '• 聚焦策略 → 小型精實、快速回應',
            '• 多角化 → 事業部制、獨立核算',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'content',
        'title': '規模與組織生命週期',
        'content': [
            '• 創業期（1~50人）：扁平、非正式、創辦人主導一切，溝通靠口耳相傳',
            '• 成長期（50~500人）：開始需要制度、部門化、中階主管出現',
            '• 成熟期（500~5000人）：官僚化風險，流程繁瑣，創新速度下降',
            '• 轉型期（5000+人）：重組、併購、事業部化，或回歸精實扁平',
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'content',
        'title': '集權 vs 分權',
        'content': [
            '集權式：決策集中在高階，命令自上而下。一致性高但回應慢。',
            '',
            '分權式：決策下放到第一線，回應快速但需成熟的管控機制。',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '跨部門協調機制',
        'content': [
            '• 整合性角色：設立專案經理、產品經理或流程負責人，專責跨部門協調。',
            '• 跨部門委員會：定期召開協調會議，處理資源分配與衝突解決。',
            '• 標準化流程：建立SOP、資訊系統與共用平台，減少人為協調需求。',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'content',
        'title': '敏捷組織設計',
        'content': [
            '敏捷組織的核心是以客戶為中心、快速迭代、持續學習。',
            '',
            '• 小型跨功能團隊（Squad / Tribe）',
            '• OKR 取代 KPI，聚焦成果而非活動',
            '• 授權第一線決策，縮短回應循環',
            '• 容忍失敗，鼓勵實驗與快速學習',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '數位時代的組織變革',
        'content': [
            '數位工具不只是技術升級，它正在重塑組織的邊界、溝通與決策方式。',
            '',
            '• 遠端協作打破地理限制',
            '• 數據驅動取代經驗直覺',
            '• 平台化讓組織從「管控」走向「賦能」',
            '• AI 輔助決策，中階主管角色轉型',
            '',
            '⚠️ 常見陷阱：「把舊流程搬到新系統」= 花錢加速混亂',
            '✅ 正確順序：先優化流程 → 再數位化 → 最後自動化',
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'content',
        'title': '組織結構與文化的關係',
        'content': [
            '結構是組織的「骨架」，文化是組織的「靈魂」。兩者必須一致，否則會產生內耗。',
            '',
            '• 扁平結構 → 需要信任與授權文化',
            '• 官僚結構 → 需要服從與紀律文化',
            '• 矩陣結構 → 需要協作與溝通文化',
            '• 敏捷結構 → 需要學習與容錯文化',
            '',
            '結構改了，文化沒改 = 穿新衣走舊路',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '組織設計常見錯誤',
        'content': [
            '• 照抄別人：別人的結構是別人策略與文化的產物，照搬往往水土不服。',
            '• 結構落後策略：策略轉型了，組織結構還停在原地，新策略無法落地。',
            '• 過度複雜：層級太多、委員會太多、流程太長，導致效率低落。',
            '• 忽視人的因素：只調整框圖，不處理能力、動機與文化，最終回到原點。',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'content',
        'title': '台灣企業的組織設計挑戰',
        'content': [
            '• 中小企業為主，資源有限，結構調整成本高',
            '• 創辦人文化深，分權意願低',
            '• 代工思維重視效率，輕視跨部門創新',
            '• 缺工與高齡化迫使組織精簡與自動化',
            '• 數位轉型需要新的協作模式與權責劃分',
            '',
            '台灣的機會：彈性強、反應快、學習意願高，正好適合導入敏捷與精實組織設計',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '組織設計導入五步驟',
        'content': [
            '1. 診斷現狀：組織圖、權責矩陣、流程效率、員工滿意度調查',
            '2. 釐清策略：未來 3~5 年策略方向，結構必須服務於策略',
            '3. 設計方案：繪製多個結構選項，評估優缺點與風險',
            '4. 導入轉型：溝通、教育訓練、試行、調整，管理變革阻力',
            '5. 持續優化：定期檢視結構有效性，因應環境變化動態調整',
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'content',
        'title': '組織設計的績效指標',
        'content': [
            '• 決策速度：↑ 40%（從提案到執行的時間）',
            '• 跨部門協作：↑ 35%（專案準時交付率）',
            '• 員工滿意：↑ 28%（角色清晰度與授權感）',
            '• 營運效率：↓ 22%（管理費用佔營收比）',
        ],
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '個案：科技公司從機能型轉矩陣型',
        'content': [
            '某 500 人科技公司，原為純機能型結構。隨著產品線擴增至 5 條，跨部門協調成為瓶頸。',
            '',
            '• 導入產品線矩陣結構',
            '• 每位工程師同時歸屬職能部門與產品團隊',
            '• 設立 PMO（專案管理辦公室）統籌資源',
            '• 半年內產品上市時間縮短 30%',
            '',
            '關鍵成功因素：CEO 親自推動，明確授權矩陣主管',
            '遇到的阻力：中階主管擔憂權力被稀釋',
            '解方：重新定義 KPI，讓雙線主管利益一致',
        ],
    },
    {
        'theme': 'theme-accent',
        'type': 'quote',
        'title': '組織設計',
        'quote': '「組織 structure follows strategy。但如果策略模糊，結構只會讓混亂更有秩序。」',
        'author': '— 改寫自 Alfred Chandler',
    },
    {
        'theme': 'theme-dark',
        'type': 'content',
        'title': '核心摘要',
        'content': [
            '• 組織設計是策略執行的基礎建設',
            '• 沒有唯一最佳結構，只有最適合的結構',
            '• 結構、策略、文化三者必須一致',
            '• 設計後需要持續檢視與動態調整',
            '• 數位工具是放大器，流程優化才是前提',
            '',
            '一句話總結：好的組織設計，讓對的人在對的位置，用對的方式做對的事',
        ],
    },
    {
        'theme': 'theme-navy',
        'type': 'ending',
        'title': 'Thank You',
        'subtitle': '組織設計 — 策略、結構與效能的系統性整合',
    },
]

def create_presentation():
    prs = Presentation()
    prs.slide_width = Inches(13.333)
    prs.slide_height = Inches(7.5)
    
    for slide_data in SLIDES:
        slide_layout = prs.slide_layouts[6]  # Blank layout
        slide = prs.slides.add_slide(slide_layout)
        
        # Set background color
        theme = THEMES[slide_data['theme']]
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = theme['bg']
        
        # Add content based on slide type
        if slide_data['type'] == 'title':
            # Title slide
            txBox = slide.shapes.add_textbox(Inches(1), Inches(2.5), Inches(11.333), Inches(2))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['title']
            p.font.size = Pt(72)
            p.font.bold = True
            p.font.color.rgb = theme['text']
            p.alignment = PP_ALIGN.CENTER
            
            # Subtitle
            p2 = tf.add_paragraph()
            p2.text = slide_data['subtitle']
            p2.font.size = Pt(28)
            p2.font.color.rgb = RGBColor(0x94, 0xA3, 0xB8)
            p2.alignment = PP_ALIGN.CENTER
            p2.space_before = Pt(24)
            
        elif slide_data['type'] == 'section':
            # Section divider
            txBox = slide.shapes.add_textbox(Inches(1), Inches(2.5), Inches(11.333), Inches(2))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['title']
            p.font.size = Pt(64)
            p.font.bold = True
            p.font.color.rgb = theme['text']
            p.alignment = PP_ALIGN.CENTER
            
            # Subtitle
            p2 = tf.add_paragraph()
            p2.text = slide_data['subtitle']
            p2.font.size = Pt(24)
            p2.font.color.rgb = RGBColor(0x94, 0xA3, 0xB8)
            p2.alignment = PP_ALIGN.CENTER
            p2.space_before = Pt(24)
            
        elif slide_data['type'] == 'content':
            # Content slide with title and bullet points
            # Title
            txBox = slide.shapes.add_textbox(Inches(0.8), Inches(0.5), Inches(11.733), Inches(1))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['title']
            p.font.size = Pt(44)
            p.font.bold = True
            p.font.color.rgb = theme['text']
            
            # Content
            txBox2 = slide.shapes.add_textbox(Inches(0.8), Inches(1.8), Inches(11.733), Inches(5))
            tf2 = txBox2.text_frame
            tf2.word_wrap = True
            
            for i, line in enumerate(slide_data['content']):
                if i == 0:
                    p = tf2.paragraphs[0]
                else:
                    p = tf2.add_paragraph()
                
                p.text = line
                p.font.size = Pt(24)
                p.font.color.rgb = theme['text']
                p.space_before = Pt(8)
                p.space_after = Pt(8)
                
                # Make bullet points slightly indented
                if line.startswith('•') or line.startswith('⚠') or line.startswith('✅') or line.startswith('1.') or line.startswith('2.') or line.startswith('3.') or line.startswith('4.') or line.startswith('5.'):
                    p.level = 0
        
        elif slide_data['type'] == 'agenda':
            # Agenda slide
            txBox = slide.shapes.add_textbox(Inches(0.8), Inches(0.5), Inches(11.733), Inches(1))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['title']
            p.font.size = Pt(44)
            p.font.bold = True
            p.font.color.rgb = theme['text']
            
            # Agenda items
            txBox2 = slide.shapes.add_textbox(Inches(0.8), Inches(1.8), Inches(11.733), Inches(5))
            tf2 = txBox2.text_frame
            tf2.word_wrap = True
            
            for i, item in enumerate(slide_data['items']):
                if i == 0:
                    p = tf2.paragraphs[0]
                else:
                    p = tf2.add_paragraph()
                
                p.text = f"{item['num']} {item['title']}"
                p.font.size = Pt(32)
                p.font.bold = True
                p.font.color.rgb = theme['accent']
                p.space_before = Pt(16)
                p.space_after = Pt(4)
                
                # Description
                p2 = tf2.add_paragraph()
                p2.text = item['desc']
                p2.font.size = Pt(20)
                p2.font.color.rgb = RGBColor(0x64, 0x74, 0x8B)
                p2.space_before = Pt(0)
                p2.space_after = Pt(16)
        
        elif slide_data['type'] == 'table':
            # Table slide
            txBox = slide.shapes.add_textbox(Inches(0.8), Inches(0.5), Inches(11.733), Inches(1))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['title']
            p.font.size = Pt(44)
            p.font.bold = True
            p.font.color.rgb = theme['text']
            
            # Create table
            rows = len(slide_data['rows']) + 1  # +1 for header
            cols = len(slide_data['headers'])
            table = slide.shapes.add_table(rows, cols, Inches(0.8), Inches(1.8), Inches(11.733), Inches(5)).table
            
            # Set column widths
            col_width = Inches(11.733 / cols)
            for i in range(cols):
                table.columns[i].width = col_width
            
            # Header row
            for i, header in enumerate(slide_data['headers']):
                cell = table.cell(0, i)
                cell.text = header
                cell.fill.solid()
                cell.fill.fore_color.rgb = RGBColor(0x4F, 0x46, 0xE5)
                cell.text_frame.paragraphs[0].font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
                cell.text_frame.paragraphs[0].font.bold = True
                cell.text_frame.paragraphs[0].font.size = Pt(18)
            
            # Data rows
            for r, row in enumerate(slide_data['rows']):
                for c, cell_text in enumerate(row):
                    cell = table.cell(r + 1, c)
                    cell.text = cell_text
                    cell.fill.solid()
                    cell.fill.fore_color.rgb = theme['bg'] if r % 2 == 0 else RGBColor(0x1E, 0x29, 0x3B)
                    cell.text_frame.paragraphs[0].font.color.rgb = theme['text']
                    cell.text_frame.paragraphs[0].font.size = Pt(16)
        
        elif slide_data['type'] == 'quote':
            # Quote slide
            txBox = slide.shapes.add_textbox(Inches(1.5), Inches(2), Inches(10.333), Inches(3))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['quote']
            p.font.size = Pt(36)
            p.font.italic = True
            p.font.color.rgb = theme['text']
            p.alignment = PP_ALIGN.CENTER
            
            # Author
            p2 = tf.add_paragraph()
            p2.text = slide_data['author']
            p2.font.size = Pt(24)
            p2.font.color.rgb = RGBColor(0x94, 0xA3, 0xB8)
            p2.alignment = PP_ALIGN.CENTER
            p2.space_before = Pt(24)
        
        elif slide_data['type'] == 'ending':
            # Ending slide
            txBox = slide.shapes.add_textbox(Inches(1), Inches(2.5), Inches(11.333), Inches(2))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]
            p.text = slide_data['title']
            p.font.size = Pt(72)
            p.font.bold = True
            p.font.color.rgb = theme['text']
            p.alignment = PP_ALIGN.CENTER
            
            # Subtitle
            p2 = tf.add_paragraph()
            p2.text = slide_data['subtitle']
            p2.font.size = Pt(24)
            p2.font.color.rgb = RGBColor(0x94, 0xA3, 0xB8)
            p2.alignment = PP_ALIGN.CENTER
            p2.space_before = Pt(24)
    
    # Save the presentation
    output_path = os.path.expanduser('~/Desktop/組織設計簡報_v3.pptx')
    prs.save(output_path)
    print(f'✅ 簡報已儲存至: {output_path}')
    return output_path

if __name__ == '__main__':
    create_presentation()