#!/usr/bin/env python
"""
Location2025テーブルの新しいフィールドを旧Locationテーブルから更新するスクリプト
"""

import os
import sys
import django

# Django設定
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rogaining_srv.settings')
django.setup()

from rog.models import Location2025, Location
from django.db import transaction

def update_location2025_from_old_location():
    """
    旧Locationテーブルから Location2025 の新しいフィールドを更新
    """
    print("=== Location2025フィールド更新開始 ===")
    
    # 更新対象のフィールドマッピング
    field_mapping = {
        'category': 'category',
        'zip_code': 'zip',  # Location2025.zip_code <- Location.zip
        'prefecture': 'prefecture',
        'area': 'area', 
        'city': 'city',
        'facility': 'facility'
    }
    
    updated_count = 0
    not_found_count = 0
    
    try:
        with transaction.atomic():
            location2025_records = Location2025.objects.all()
            total_records = location2025_records.count()
            
            print(f"処理対象レコード数: {total_records}")
            
            for i, loc2025 in enumerate(location2025_records, 1):
                if i % 100 == 0:
                    print(f"進行状況: {i}/{total_records}")
                
                # location_idまたはcp_nameで旧Locationテーブルから対応するレコードを検索
                old_location = None
                
                # まずlocation_idで検索（sub_loc_idがlocation_idの可能性）
                if loc2025.sub_loc_id:
                    try:
                        location_id = int(loc2025.sub_loc_id)
                        old_location = Location.objects.filter(location_id=location_id).first()
                    except (ValueError, TypeError):
                        pass
                
                # location_idで見つからない場合、location_nameで検索
                if not old_location:
                    old_location = Location.objects.filter(location_name=loc2025.cp_name).first()
                
                # 部分一致で検索
                if not old_location and loc2025.cp_name:
                    old_location = Location.objects.filter(location_name__icontains=loc2025.cp_name).first()
                
                if old_location:
                    # フィールドを更新
                    updated = False
                    for loc2025_field, location_field in field_mapping.items():
                        if hasattr(old_location, location_field):
                            old_value = getattr(old_location, location_field)
                            if old_value:  # 値が存在する場合のみ更新
                                # zip_codeの場合、〒記号を除去
                                if loc2025_field == 'zip_code' and old_value.startswith('〒'):
                                    old_value = old_value[1:]
                                
                                setattr(loc2025, loc2025_field, old_value)
                                updated = True
                    
                    if updated:
                        loc2025.save()
                        updated_count += 1
                        
                        if i <= 5:  # 最初の5件の詳細を表示
                            print(f"  更新: CP{loc2025.cp_number} {loc2025.cp_name}")
                            print(f"    Category: {loc2025.category}")
                            print(f"    Area: {loc2025.area}, Prefecture: {loc2025.prefecture}")
                            print(f"    City: {loc2025.city}, Zip: {loc2025.zip_code}")
                            print(f"    Facility: {loc2025.facility}")
                
                else:
                    not_found_count += 1
                    if not_found_count <= 5:  # 最初の5件のエラーを表示
                        print(f"  見つからない: CP{loc2025.cp_number} {loc2025.cp_name} (sub_loc_id: {loc2025.sub_loc_id})")
            
            print(f"\n=== 更新完了 ===")
            print(f"更新されたレコード数: {updated_count}")
            print(f"対応するLocationが見つからないレコード数: {not_found_count}")
            
            # 更新結果のサンプルを表示
            print(f"\n=== 更新後サンプル ===")
            updated_samples = Location2025.objects.exclude(category__isnull=True).exclude(category='')[:3]
            for sample in updated_samples:
                print(f"CP{sample.cp_number}: {sample.cp_name}")
                print(f"  Category: {sample.category}")
                print(f"  Location: {sample.prefecture} {sample.area} {sample.city}")
                print(f"  Zip: {sample.zip_code}, Facility: {sample.facility}")
                print()
                
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        raise

if __name__ == "__main__":
    update_location2025_from_old_location()
