#!/usr/bin/env python3
"""批量更新 vendor_stockout 系列頁面的導航列"""

import re
from pathlib import Path

NEW_NAVBAR = '''    <!-- 導航列 -->
    <nav class="navbar navbar-expand-xl navbar-dark bg-dark mb-4 shadow-sm">
        <div class="container-fluid">
            <a class="navbar-brand" href="/"><i class="fas fa-chart-line me-2"></i>MOMO 監控系統</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"><a class="nav-link" href="/"><i class="fas fa-chart-line me-1"></i>商品看板</a></li>
                    <li class="nav-item"><a class="nav-link" href="/edm"><i class="fas fa-bullhorn me-1"></i>活動看板</a></li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" 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" href="/vendor-stockout"><i class="fas fa-box-open me-1"></i>廠商缺貨</a></li>
                    <li class="nav-item"><a class="nav-link" 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" 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-cog 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><span id="nav-time"></span>
                </span>
            </div>
        </div>
    </nav>'''

TIME_SCRIPT = '''        // 更新導航列時鐘
        function updateNavTime() {
            const now = new Date();
            const elem = document.getElementById('nav-time');
            if (elem) {
                elem.textContent = now.toLocaleString('zh-TW', {
                    year: 'numeric', month: '2-digit', day: '2-digit',
                    hour: '2-digit', minute: '2-digit', second: '2-digit'
                });
            }
        }
        updateNavTime();
        setInterval(updateNavTime, 1000);'''

def update_file(filepath):
    """更新單個文件"""
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()

    # 替換導航列（從 <!-- 導航列 --> 或 <nav 到 </nav> 之後的空行）
    pattern = r'(<!--\s*導航列\s*-->)?\s*<nav class="navbar.*?</nav>\s*'
    new_content = re.sub(pattern, NEW_NAVBAR + '\n\n', content, count=1, flags=re.DOTALL)

    # 添加時鐘腳本（在 </body> 前）
    if 'updateNavTime' not in new_content and '</body>' in new_content:
        new_content = new_content.replace('</body>', f'    <script>\n{TIME_SCRIPT}\n    </script>\n</body>')

    if new_content != content:
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print(f"✅ 已更新 {filepath.name}")
        return True
    else:
        print(f"⏭️  跳過 {filepath.name}")
        return False

def main():
    base_dir = Path(__file__).parent
    vendor_files = list(base_dir.glob('vendor_stockout_*.html'))

    print(f"找到 {len(vendor_files)} 個廠商缺貨頁面文件")
    print("=" * 50)

    updated = 0
    for filepath in sorted(vendor_files):
        if update_file(filepath):
            updated += 1

    print("=" * 50)
    print(f"✅ 完成！更新了 {updated} 個文件")

if __name__ == '__main__':
    main()
