#!/usr/bin/env python3
import os
import sys
import django

# プロジェクト設定
sys.path.append('/app')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.db import connection
import logging

# ログ設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def analyze_event_data_raw():
    """生のSQLを使ってイベント・チーム・エントリーデータを分析"""
    
    print("=== 生SQLによるイベント・データ分析 ===")
    
    with connection.cursor() as cursor:
        # 1. NewEvent2テーブルの構造確認
        print("\n1. rog_newevent2テーブル構造:")
        cursor.execute("""
            SELECT column_name, data_type, is_nullable 
            FROM information_schema.columns 
            WHERE table_name = 'rog_newevent2' 
            ORDER BY ordinal_position;
        """)
        columns = cursor.fetchall()
        for col in columns:
            print(f"  - {col[0]}: {col[1]} ({'NULL' if col[2] == 'YES' else 'NOT NULL'})")
        
        # 2. 全イベント一覧
        print("\n2. 全イベント一覧:")
        cursor.execute("""
            SELECT id, event_name, event_day, venue_address 
            FROM rog_newevent2 
            ORDER BY id;
        """)
        events = cursor.fetchall()
        
        for event in events:
            print(f"  - ID:{event[0]}, Name:{event[1]}, Date:{event[2]}, Venue:{event[3]}")
            
            # 各イベントのエントリー数とチーム数
            cursor.execute("SELECT COUNT(*) FROM rog_entry WHERE event_id = %s", [event[0]])
            entry_count = cursor.fetchone()[0]
            
            cursor.execute("SELECT COUNT(*) FROM rog_team WHERE event_id = %s", [event[0]])
            team_count = cursor.fetchone()[0]
            
            print(f"    Entry:{entry_count}, Team:{team_count}")
        
        # 3. FC岐阜関連イベント検索
        print("\n3. FC岐阜関連イベント検索:")
        cursor.execute("""
            SELECT id, event_name, event_day, venue_address 
            FROM rog_newevent2 
            WHERE event_name ILIKE %s OR event_name ILIKE %s OR event_name ILIKE %s
            ORDER BY id;
        """, ['%FC岐阜%', '%fc岐阜%', '%岐阜%'])
        
        fc_events = cursor.fetchall()
        if fc_events:
            for event in fc_events:
                print(f"  - ID:{event[0]}, Name:{event[1]}, Date:{event[2]}")
                
                # 関連エントリー
                cursor.execute("""
                    SELECT e.id, t.id as team_id, t.name as team_name, t.zekken_number 
                    FROM rog_entry e 
                    JOIN rog_team t ON e.team_id = t.id 
                    WHERE e.event_id = %s 
                    LIMIT 10;
                """, [event[0]])
                
                entries = cursor.fetchall()
                if entries:
                    print("    エントリー詳細:")
                    for entry in entries:
                        print(f"      Entry ID:{entry[0]}, Team ID:{entry[1]}, Team:{entry[2]}, Zekken:{entry[3]}")
                
                # 関連チーム（ゼッケン番号付き）
                cursor.execute("""
                    SELECT id, name, zekken_number 
                    FROM rog_team 
                    WHERE event_id = %s AND zekken_number IS NOT NULL AND zekken_number != ''
                    LIMIT 10;
                """, [event[0]])
                
                teams_with_zekken = cursor.fetchall()
                if teams_with_zekken:
                    print("    ゼッケン番号付きチーム:")
                    for team in teams_with_zekken:
                        print(f"      Team ID:{team[0]}, Name:{team[1]}, Zekken:{team[2]}")
                else:
                    print("    ゼッケン番号付きチームが見つかりません")
        else:
            print("  FC岐阜関連イベントが見つかりません")
        
        # 4. 全体のゼッケン番号付きチーム確認
        print("\n4. 全体のゼッケン番号付きチーム状況:")
        cursor.execute("""
            SELECT COUNT(*) 
            FROM rog_team 
            WHERE zekken_number IS NOT NULL AND zekken_number != '';
        """)
        zekken_team_count = cursor.fetchone()[0]
        print(f"  ゼッケン番号付きチーム総数: {zekken_team_count}")
        
        if zekken_team_count > 0:
            cursor.execute("""
                SELECT t.id, t.name, t.zekken_number, e.event_name 
                FROM rog_team t 
                LEFT JOIN rog_newevent2 e ON t.event_id = e.id 
                WHERE t.zekken_number IS NOT NULL AND t.zekken_number != ''
                LIMIT 10;
            """)
            
            sample_teams = cursor.fetchall()
            print("  サンプル:")
            for team in sample_teams:
                print(f"    ID:{team[0]}, Name:{team[1]}, Zekken:{team[2]}, Event:{team[3]}")
        
        # 5. 通過審査管理画面で使われる可能性のあるクエリの確認
        print("\n5. 通過審査管理用データ確認:")
        cursor.execute("""
            SELECT e.id as event_id, e.event_name, COUNT(t.id) as team_count, 
                   COUNT(CASE WHEN t.zekken_number IS NOT NULL AND t.zekken_number != '' THEN 1 END) as zekken_teams
            FROM rog_newevent2 e 
            LEFT JOIN rog_team t ON e.id = t.event_id 
            GROUP BY e.id, e.event_name 
            ORDER BY e.id;
        """)
        
        event_stats = cursor.fetchall()
        print("  イベント別チーム・ゼッケン統計:")
        for stat in event_stats:
            print(f"    イベントID:{stat[0]}, Name:{stat[1]}, 総チーム:{stat[2]}, ゼッケン付き:{stat[3]}")

if __name__ == "__main__":
    try:
        analyze_event_data_raw()
    except Exception as e:
        print(f"❌ エラーが発生しました: {e}")
        import traceback
        traceback.print_exc()
