#!/usr/bin/env python
"""
old_rogdb構造分析＆データ移行準備スクリプト
old_rogdbの構造を詳細に分析し、rogdbへの移行計画を立てる
"""

import os
import sys
import django
import psycopg2

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
    django.setup()
    
    from django.conf import settings
    
    print("=== old_rogdb構造分析 ===")
    
    # old_rogdb直接接続設定
    old_db_config = {
        'host': 'postgres-db',
        'database': 'old_rogdb',
        'user': 'admin',
        'password': 'admin123456',
        'port': 5432
    }
    
    try:
        # old_rogdbに直接接続
        old_conn = psycopg2.connect(**old_db_config)
        old_cursor = old_conn.cursor()
        
        print("✅ old_rogdb接続成功")
        
        print("\\n=== 1. old_rogdb rog_entry構造分析 ===")
        old_cursor.execute("""
            SELECT column_name, data_type, is_nullable, column_default
            FROM information_schema.columns 
            WHERE table_name = 'rog_entry' AND table_schema = 'public'
            ORDER BY ordinal_position;
        """)
        old_entry_columns = old_cursor.fetchall()
        
        print("old_rogdb.rog_entry 構造:")
        for col_name, data_type, nullable, default in old_entry_columns:
            print(f"  - {col_name}: {data_type} {'(NULL可)' if nullable == 'YES' else '(NOT NULL)'} {f'[default: {default}]' if default else ''}")
        
        # old_rogdb rog_entry データ確認
        old_cursor.execute("SELECT COUNT(*) FROM rog_entry;")
        old_entry_count = old_cursor.fetchone()[0]
        print(f"\\nold_rogdb.rog_entry データ件数: {old_entry_count}件")
        
        # サンプルデータ確認
        old_cursor.execute("SELECT * FROM rog_entry LIMIT 3;")
        old_entry_samples = old_cursor.fetchall()
        print("\\nサンプルデータ（最初の3件）:")
        for i, row in enumerate(old_entry_samples):
            print(f"  Row {i+1}: {row}")
        
        print("\\n=== 2. old_rogdb rog_team構造分析 ===")
        old_cursor.execute("""
            SELECT column_name, data_type, is_nullable, column_default
            FROM information_schema.columns 
            WHERE table_name = 'rog_team' AND table_schema = 'public'
            ORDER BY ordinal_position;
        """)
        old_team_columns = old_cursor.fetchall()
        
        print("old_rogdb.rog_team 構造:")
        for col_name, data_type, nullable, default in old_team_columns:
            print(f"  - {col_name}: {data_type} {'(NULL可)' if nullable == 'YES' else '(NOT NULL)'} {f'[default: {default}]' if default else ''}")
        
        old_cursor.execute("SELECT COUNT(*) FROM rog_team;")
        old_team_count = old_cursor.fetchone()[0]
        print(f"\\nold_rogdb.rog_team データ件数: {old_team_count}件")
        
        print("\\n=== 3. old_rogdb rog_member構造分析 ===")
        try:
            old_cursor.execute("""
                SELECT column_name, data_type, is_nullable, column_default
                FROM information_schema.columns 
                WHERE table_name = 'rog_member' AND table_schema = 'public'
                ORDER BY ordinal_position;
            """)
            old_member_columns = old_cursor.fetchall()
            
            if old_member_columns:
                print("old_rogdb.rog_member 構造:")
                for col_name, data_type, nullable, default in old_member_columns:
                    print(f"  - {col_name}: {data_type} {'(NULL可)' if nullable == 'YES' else '(NOT NULL)'} {f'[default: {default}]' if default else ''}")
                
                old_cursor.execute("SELECT COUNT(*) FROM rog_member;")
                old_member_count = old_cursor.fetchone()[0]
                print(f"\\nold_rogdb.rog_member データ件数: {old_member_count}件")
            else:
                print("old_rogdb.rog_member テーブルが存在しません")
        except Exception as e:
            print(f"old_rogdb.rog_member 確認エラー: {e}")
        
        print("\\n=== 4. FC岐阜関連データ詳細分析 ===")
        
        # FC岐阜イベント確認
        old_cursor.execute("""
            SELECT id, event_name, start_datetime, end_datetime
            FROM rog_newevent2 
            WHERE event_name LIKE '%FC岐阜%' OR event_name LIKE '%fc岐阜%'
            ORDER BY id;
        """)
        fc_events = old_cursor.fetchall()
        
        print("FC岐阜関連イベント:")
        for event_id, name, start, end in fc_events:
            print(f"  Event {event_id}: '{name}' ({start} - {end})")
            
            # このイベントのエントリー数確認
            old_cursor.execute("SELECT COUNT(*) FROM rog_entry WHERE event_id = %s;", (event_id,))
            entry_count = old_cursor.fetchone()[0]
            print(f"    エントリー数: {entry_count}件")
        
        # FC岐阜イベントのエントリー詳細
        if fc_events:
            fc_event_id = fc_events[0][0]  # 最初のFC岐阜イベント
            print(f"\\nFC岐阜イベント(ID:{fc_event_id})のエントリー詳細:")
            
            old_cursor.execute("""
                SELECT re.id, re.team_id, re.category_id, re.zekken_number, re.zekken_label,
                       rt.team_name, rc.category_name
                FROM rog_entry re
                JOIN rog_team rt ON re.team_id = rt.id
                LEFT JOIN rog_newcategory rc ON re.category_id = rc.id
                WHERE re.event_id = %s
                ORDER BY re.zekken_number
                LIMIT 10;
            """, (fc_event_id,))
            
            fc_entry_details = old_cursor.fetchall()
            for entry_id, team_id, cat_id, zekken, label, team_name, cat_name in fc_entry_details:
                print(f"  Entry {entry_id}: Team {team_id}({team_name}) - ゼッケン{zekken} - {cat_name}")
        
        print("\\n=== 5. 移行計画 ===")
        print("移行が必要なテーブル:")
        print("  1. old_rogdb.rog_team → rogdb.rog_team")
        print("  2. old_rogdb.rog_entry → rogdb.rog_entry")
        print("  3. old_rogdb.rog_member → rogdb.rog_member (存在する場合)")
        print("\\n注意点:")
        print("  - イベントはrog_newevent2を使用")
        print("  - 外部キー制約の整合性確保")
        print("  - データ型の変換（必要に応じて）")
        print("  - 重複データの回避")
        
        old_cursor.close()
        old_conn.close()
        
    except Exception as e:
        print(f"❌ エラーが発生しました: {e}")
        import traceback
        traceback.print_exc()
