#!/usr/bin/env python
"""
SQL直接実行版: 最近のGpsLogとCheckinImagesデータを表示
Docker環境で動作
"""

import subprocess
import sys
import json
from datetime import datetime, timedelta

def run_db_query(query):
    """
    PostgreSQLクエリを実行
    """
    try:
        cmd = [
            'docker-compose', 'exec', '-T', 'postgres-db', 
            'psql', '-U', 'admin', '-d', 'rogdb', 
            '-c', query
        ]
        
        result = subprocess.run(
            cmd, 
            capture_output=True, 
            text=True
        )
        
        if result.returncode == 0:
            return result.stdout
        else:
            print(f"❌ SQLエラー: {result.stderr}")
            return None
            
    except Exception as e:
        print(f"❌ 実行エラー: {e}")
        return None

def show_recent_gpslog(days=7):
    """
    最近のGpsLogデータを表示
    """
    print(f"\n📍 GpsLog (過去{days}日間)")
    print("-" * 80)
    
    query = f"""
    SELECT 
        id,
        to_char(checkin_time, 'MM-DD HH24:MI:SS') as time,
        zekken_number,
        event_code,
        cp_number,
        CASE 
            WHEN image_address IS NOT NULL AND image_address != '' THEN '✅'
            ELSE '❌'
        END as has_image,
        CASE 
            WHEN length(image_address) > 50 THEN left(image_address, 47) || '...'
            ELSE coalesce(image_address, '')
        END as image_preview
    FROM rog_gpslog 
    WHERE checkin_time >= NOW() - INTERVAL '{days} days'
    ORDER BY checkin_time DESC 
    LIMIT 20;
    """
    
    result = run_db_query(query)
    if result:
        print(result)
    
def show_recent_checkinimages(days=7):
    """
    最近のCheckinImagesデータを表示
    """
    print(f"\n🖼️  CheckinImages (過去{days}日間)")
    print("-" * 80)
    
    query = f"""
    SELECT 
        ci.id,
        to_char(ci.checkintime, 'MM-DD HH24:MI:SS') as time,
        left(cu.email, 15) as user_email,
        left(ci.team_name, 12) as team,
        left(ci.event_code, 10) as event,
        ci.cp_number,
        CASE 
            WHEN ci.checkinimage IS NOT NULL AND ci.checkinimage != '' THEN '✅'
            ELSE '❌'
        END as has_file,
        CASE 
            WHEN length(ci.checkinimage::text) > 30 THEN left(ci.checkinimage::text, 27) || '...'
            ELSE coalesce(ci.checkinimage::text, '')
        END as file_preview
    FROM rog_checkinimages ci
    LEFT JOIN auth_user cu ON ci.user_id = cu.id
    WHERE ci.checkintime >= NOW() - INTERVAL '{days} days'
    ORDER BY ci.checkintime DESC 
    LIMIT 20;
    """
    
    result = run_db_query(query)
    if result:
        print(result)

def show_table_stats():
    """
    テーブル統計情報を表示
    """
    print(f"\n📊 テーブル統計")
    print("-" * 50)
    
    query = """
    SELECT 
        'GpsLog' as table_name,
        count(*) as total_count,
        count(CASE WHEN image_address IS NOT NULL AND image_address != '' THEN 1 END) as with_image,
        to_char(min(checkin_time), 'YYYY-MM-DD') as oldest_date,
        to_char(max(checkin_time), 'YYYY-MM-DD HH24:MI') as latest_date
    FROM rog_gpslog
    UNION ALL
    SELECT 
        'CheckinImages' as table_name,
        count(*) as total_count,
        count(CASE WHEN checkinimage IS NOT NULL AND checkinimage != '' THEN 1 END) as with_file,
        to_char(min(checkintime), 'YYYY-MM-DD') as oldest_date,
        to_char(max(checkintime), 'YYYY-MM-DD HH24:MI') as latest_date
    FROM rog_checkinimages;
    """
    
    result = run_db_query(query)
    if result:
        print(result)

def show_event_stats():
    """
    イベント別統計を表示
    """
    print(f"\n🎯 イベント別統計 (GpsLog)")
    print("-" * 40)
    
    query = """
    SELECT 
        event_code,
        count(*) as checkin_count,
        count(CASE WHEN image_address IS NOT NULL AND image_address != '' THEN 1 END) as with_image_count,
        to_char(min(checkin_time), 'MM-DD') as first_checkin,
        to_char(max(checkin_time), 'MM-DD') as last_checkin
    FROM rog_gpslog
    GROUP BY event_code
    ORDER BY checkin_count DESC
    LIMIT 10;
    """
    
    result = run_db_query(query)
    if result:
        print(result)
    
    print(f"\n🖼️  イベント別統計 (CheckinImages)")
    print("-" * 40)
    
    query = """
    SELECT 
        event_code,
        count(*) as image_count,
        count(DISTINCT team_name) as unique_teams,
        to_char(min(checkintime), 'MM-DD') as first_image,
        to_char(max(checkintime), 'MM-DD') as last_image
    FROM rog_checkinimages
    GROUP BY event_code
    ORDER BY image_count DESC
    LIMIT 10;
    """
    
    result = run_db_query(query)
    if result:
        print(result)

def show_recent_activity():
    """
    最近のアクティビティを時系列で表示
    """
    print(f"\n⏰ 最近のアクティビティ (時系列)")
    print("-" * 60)
    
    query = """
    (
        SELECT 
            'GpsLog' as source,
            checkin_time as timestamp,
            zekken_number as identifier,
            event_code,
            cp_number,
            CASE WHEN image_address IS NOT NULL AND image_address != '' THEN 'with_image' ELSE 'no_image' END as note
        FROM rog_gpslog
        WHERE checkin_time >= NOW() - INTERVAL '24 hours'
    )
    UNION ALL
    (
        SELECT 
            'CheckinImages' as source,
            checkintime as timestamp,
            team_name as identifier,
            event_code,
            cp_number::text,
            'image_upload' as note
        FROM rog_checkinimages
        WHERE checkintime >= NOW() - INTERVAL '24 hours'
    )
    ORDER BY timestamp DESC
    LIMIT 15;
    """
    
    result = run_db_query(query)
    if result:
        print(result)

def main():
    """
    メイン関数
    """
    print("🏃‍♂️ ロゲイニング チェックインデータ表示ツール (SQL版)")
    print("=" * 80)
    
    # 引数処理
    days = 7
    if len(sys.argv) > 1:
        try:
            days = int(sys.argv[1])
        except ValueError:
            print("⚠️  日数は数値で指定してください (デフォルト: 7日)")
            days = 7
    
    print(f"📅 過去{days}日間のデータを表示します")
    
    # データ表示
    show_recent_gpslog(days)
    show_recent_checkinimages(days)
    show_table_stats()
    show_event_stats()
    show_recent_activity()
    
    print(f"\n✅ 完了")
    print(f"\n使用方法: python3 {sys.argv[0]} [日数]")
    print(f"例: python3 {sys.argv[0]} 3  # 過去3日間のデータ")

if __name__ == '__main__':
    main()
