#!/usr/bin/env python3
"""
修復所有 HTML 文件的導航列，移除重複項目
"""
import os
import re
from pathlib import Path

# 標準導航列模板
STANDARD_NAVBAR = '''            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"><a class="nav-link{active_dashboard}" href="/"><i class="fas fa-chart-line me-1"></i>商品看板</a></li>
                    <li class="nav-item"><a class="nav-link{active_edm}" href="/edm"><i class="fas fa-bullhorn me-1"></i>活動看板</a></li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle{active_analysis}" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-chart-bar me-1"></i>分析報表
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/sales_analysis"><i class="fas fa-chart-bar me-2"></i>業績分析</a></li>
                            <li><a class="dropdown-item" href="/daily_sales"><i class="fas fa-calendar-day me-2"></i>當日業績</a></li>
                        </ul>
                    </li>
                    <li class="nav-item"><a class="nav-link{active_vendor}" href="/vendor-stockout"><i class="fas fa-box-open me-1"></i>廠商缺貨</a></li>
                    <li class="nav-item"><a class="nav-link{active_import}" href="/auto_import"><i class="fas fa-cloud-download-alt me-1"></i>雲端匯入</a></li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle{active_system}" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-cog me-1"></i>系統管理
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/settings"><i class="fas fa-robot me-2"></i>爬蟲管理</a></li>
                            <li><a class="dropdown-item" href="/system_settings"><i class="fas fa-sliders-h me-2"></i>系統設定</a></li>
                            <li><a class="dropdown-item" href="/logs"><i class="fas fa-file-alt me-2"></i>系統日誌</a></li>
                        </ul>
                    </li>
                </ul>
                <span class="navbar-text text-light small">
                    <i class="fas fa-clock me-1"></i>{{ datetime_now }}
                </span>
            </div>'''

# 頁面 active 標記映射
PAGE_ACTIVE_MAP = {
    'dashboard.html': {'active_dashboard': ' active'},
    'edm_dashboard.html': {'active_edm': ' {% if current_promo_page in [\'edm\', \'festival\'] %}active{% endif %}'},
    'sales_analysis.html': {'active_analysis': ' active'},
    'daily_sales.html': {'active_analysis': ' active'},
    'vendor_stockout_index.html': {'active_vendor': ' active'},
    'vendor_stockout_list.html': {'active_vendor': ' active'},
    'vendor_stockout_import.html': {'active_vendor': ' active'},
    'vendor_stockout_send_email.html': {'active_vendor': ' active'},
    'vendor_stockout_history.html': {'active_vendor': ' active'},
    'auto_import_index.html': {'active_import': ' active'},
    'settings.html': {'active_system': ' active'},
    'system_settings.html': {'active_system': ' active'},
    'logs.html': {'active_system': ' active'},
    'growth_analysis.html': {},
}

def fix_navbar(file_path):
    """修復單個 HTML 文件的導航列"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 檢查是否有導航列
    if '<div class="collapse navbar-collapse" id="navbarNav">' not in content:
        print(f"⏭️  跳過 {file_path.name}（沒有導航列）")
        return False

    # 準備導航列內容
    filename = file_path.name
    active_map = PAGE_ACTIVE_MAP.get(filename, {})

    navbar = STANDARD_NAVBAR
    navbar = navbar.replace('{active_dashboard}', active_map.get('active_dashboard', ''))
    navbar = navbar.replace('{active_edm}', active_map.get('active_edm', ''))
    navbar = navbar.replace('{active_analysis}', active_map.get('active_analysis', ''))
    navbar = navbar.replace('{active_vendor}', active_map.get('active_vendor', ''))
    navbar = navbar.replace('{active_import}', active_map.get('active_import', ''))
    navbar = navbar.replace('{active_system}', active_map.get('active_system', ''))

    # 使用正則替換整個 navbar-collapse div
    pattern = r'<div class="collapse navbar-collapse" id="navbarNav">.*?</div>\s*</div>\s*</nav>'
    replacement = navbar + '\n        </div>\n    </nav>'

    new_content = re.sub(pattern, replacement, content, flags=re.DOTALL)

    if new_content == content:
        print(f"⚠️  {file_path.name} 替換失敗")
        return False

    # 寫回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(new_content)

    print(f"✅ 已修復 {file_path.name}")
    return True

def main():
    """主程序"""
    base_dir = Path(__file__).parent
    html_files = list(base_dir.glob('*.html'))

    print(f"找到 {len(html_files)} 個 HTML 文件")
    print("=" * 50)

    fixed_count = 0
    for file_path in sorted(html_files):
        if fix_navbar(file_path):
            fixed_count += 1

    print("=" * 50)
    print(f"\n✅ 完成！修復了 {fixed_count} 個文件")

if __name__ == "__main__":
    main()
