#!/usr/bin/env python
"""
LocationからLocation2025への完全データ移行スクリプト

条件：
- NewEvent2ごとにlocation.groupにそのevent_codeが含まれているものを抽出
- location.cpをlocation2025.cp_numberに変換
- location2025.event_idにはnewevent2.idを代入

実行前にlocation2025のデータを削除してから実行
"""

from rog.models import Location, Location2025, NewEvent2

def main():
    print("=== Location から Location2025 への完全データ移行 ===")
    
    # 1. Location2025の既存データを削除
    print("\n1. Location2025の既存データを削除中...")
    deleted_count = Location2025.objects.count()
    Location2025.objects.all().delete()
    print(f"   削除済み: {deleted_count}件")
    
    # 2. NewEvent2のevent_codeマップを作成
    print("\n2. NewEvent2のevent_codeマップを作成中...")
    
    events = NewEvent2.objects.filter(event_code__isnull=False).exclude(event_code='')
    event_code_map = {}
    for event in events:
        event_code_map[event.event_code] = event
        print(f"   Event_code: '{event.event_code}' -> ID: {event.id} ({event.event_name})")
    
    print(f"   有効なevent_code数: {len(event_code_map)}件")
    
    # 3. 全Locationを取得
    print("\n3. 移行対象のLocationレコードを取得中...")
    locations = Location.objects.all()
    print(f"   総Location数: {locations.count()}件")
    
    # 4. 条件に合致するLocationを移行
    print("\n4. データ移行中...")
    
    migrated_count = 0
    skipped_count = 0
    error_count = 0
    
    for location in locations:
        try:
            # groupが空の場合はスキップ
            if not location.group:
                skipped_count += 1
                continue
            
            # location.groupに含まれるevent_codeを検索
            matched_event = None
            matched_event_code = None
            
            for event_code, event in event_code_map.items():
                if event_code in location.group:
                    matched_event = event
                    matched_event_code = event_code
                    break
            
            # マッチするevent_codeがない場合はスキップ
            if not matched_event:
                skipped_count += 1
                continue
            
            # Location2025レコードを作成
            location2025 = Location2025(
                cp_number=location.cp,  # cpをcp_numberに代入
                name=location.location_name,  # location_nameを使用
                description=location.address or '',  # addressをdescriptionとして使用
                latitude=location.latitude,
                longitude=location.longitude,
                point=location.checkin_point,  # checkin_pointをpointとして使用
                geom=location.geom,
                sub_loc_id=location.sub_loc_id,
                subcategory=location.subcategory,
                event_id=matched_event.id,  # NewEvent2のIDを設定
                created_at=location.created_at,
                updated_at=location.last_updated_at,
            )
            
            location2025.save()
            
            print(f"   ✅ 移行完了: {location.cp} -> {location2025.cp_number} ({location.location_name}) [Event: {matched_event_code}]")
            migrated_count += 1
            
        except Exception as e:
            print(f"   ❌ エラー: {location.cp} - {str(e)}")
            error_count += 1
    
    # 5. 結果サマリー
    print(f"\n=== 移行結果サマリー ===")
    print(f"移行完了: {migrated_count}件")
    print(f"スキップ: {skipped_count}件")
    print(f"エラー: {error_count}件")
    print(f"総処理: {migrated_count + skipped_count + error_count}件")
    
    # 6. Location2025の最終件数確認
    final_count = Location2025.objects.count()
    print(f"\nLocation2025最終件数: {final_count}件")
    
    # 7. event_id別の統計
    print(f"\n=== event_id別統計 ===")
    for event_code, event in event_code_map.items():
        count = Location2025.objects.filter(event_id=event.id).count()
        print(f"   Event '{event_code}' (ID: {event.id}): {count}件")
    
    if migrated_count > 0:
        print("\n✅ データ移行が正常に完了しました")
    else:
        print("\n⚠️  移行されたデータがありません")

if __name__ == "__main__":
    main()

if __name__ == "__main__":
    main()
