#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修正資料庫中的 import_date 欄位
將所有 1970-01-01 的日期更新為今天
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from database.vendor_manager import VendorDatabaseManager
from database.vendor_models import VendorStockout
from datetime import date

def fix_import_dates():
    """修正 import_date 欄位"""

    db = VendorDatabaseManager()
    session = db.get_session()

    try:
        # 查詢所有 import_date 為 1970-01-01 的記錄
        bad_date = date(1970, 1, 1)
        records = session.query(VendorStockout).filter(
            VendorStockout.import_date == bad_date
        ).all()

        print("=" * 80)
        print(f"修正 import_date 欄位")
        print("=" * 80)

        if not records:
            print("\n✅ 沒有需要修正的記錄（所有日期都正確）")
            return

        print(f"\n找到 {len(records)} 筆需要修正的記錄")
        print(f"將日期從 1970-01-01 更新為今天: {date.today()}")
        print("\n確定要更新嗎？(y/n): ", end='')

        response = input().strip().lower()
        if response != 'y':
            print("❌ 已取消")
            return

        # 更新記錄
        today = date.today()
        updated_count = 0

        for record in records:
            record.import_date = today
            updated_count += 1

            if updated_count % 10 == 0:
                print(f"  已更新 {updated_count}/{len(records)} 筆...")

        # 提交變更
        session.commit()

        print(f"\n✅ 成功更新 {updated_count} 筆記錄")
        print(f"   新日期: {today}")

        print("\n" + "=" * 80)
        print("修正完成！")
        print("=" * 80)

    except Exception as e:
        session.rollback()
        print(f"\n❌ 錯誤: {e}")
        import traceback
        traceback.print_exc()
    finally:
        session.close()

if __name__ == '__main__':
    fix_import_dates()
