#!/usr/bin/env python3
"""
日历内容记录表创建脚本
用于创建、检查和删除calendar_records表
"""

import sys
import os
import logging
from datetime import datetime

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from app import create_app, db
from sqlalchemy import text

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('calendar_records_migration.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)


def create_calendar_records_table():
    """
    创建日历内容记录表
    
    Returns:
        bool: 创建成功返回True，失败返回False
    """
    try:
        app = create_app()
        with app.app_context():
            logger.info("开始创建日历内容记录表...")
            
            # 读取DDL脚本
            sql_file_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
                'database', 'create_calendar_records.sql'
            )
            
            if not os.path.exists(sql_file_path):
                logger.error(f"DDL脚本文件不存在: {sql_file_path}")
                return False
            
            with open(sql_file_path, 'r', encoding='utf-8') as f:
                sql_content = f.read()
            
            # 执行DDL脚本
            with db.engine.connect() as connection:
                # 分割SQL语句并逐个执行
                sql_statements = [stmt.strip() for stmt in sql_content.split(';') if stmt.strip()]
                
                for statement in sql_statements:
                    if statement:
                        logger.debug(f"执行SQL: {statement[:100]}...")
                        connection.execute(text(statement))
                
                connection.commit()
            
            logger.info("日历内容记录表创建成功")
            return True
            
    except Exception as e:
        logger.error(f"创建日历内容记录表失败: {str(e)}", exc_info=True)
        return False


def check_calendar_records_table():
    """
    检查日历内容记录表是否存在
    
    Returns:
        bool: 表存在返回True，不存在返回False
    """
    try:
        app = create_app()
        with app.app_context():
            logger.info("检查日历内容记录表是否存在...")
            
            with db.engine.connect() as connection:
                result = connection.execute(text("""
                    SELECT EXISTS (
                        SELECT FROM information_schema.tables 
                        WHERE table_schema = 'public' 
                        AND table_name = 'calendar_records'
                    );
                """))
                
                exists = result.scalar()
                
                if exists:
                    logger.info("日历内容记录表已存在")
                    
                    # 获取表结构信息
                    result = connection.execute(text("""
                        SELECT column_name, data_type, is_nullable, column_default
                        FROM information_schema.columns
                        WHERE table_schema = 'public' AND table_name = 'calendar_records'
                        ORDER BY ordinal_position;
                    """))
                    
                    columns = result.fetchall()
                    logger.info("表结构:")
                    for col in columns:
                        logger.info(f"  {col[0]}: {col[1]} ({'NULL' if col[2] == 'YES' else 'NOT NULL'}) {col[3] or ''}")
                        
                    # 获取索引信息
                    result = connection.execute(text("""
                        SELECT indexname, indexdef
                        FROM pg_indexes
                        WHERE tablename = 'calendar_records' AND schemaname = 'public';
                    """))
                    
                    indexes = result.fetchall()
                    if indexes:
                        logger.info("索引:")
                        for idx in indexes:
                            logger.info(f"  {idx[0]}: {idx[1]}")
                else:
                    logger.info("日历内容记录表不存在")
                
                return exists
                
    except Exception as e:
        logger.error(f"检查日历内容记录表失败: {str(e)}", exc_info=True)
        return False


def drop_calendar_records_table():
    """
    删除日历内容记录表
    
    Returns:
        bool: 删除成功返回True，失败返回False
    """
    try:
        app = create_app()
        with app.app_context():
            logger.info("开始删除日历内容记录表...")
            
            with db.engine.connect() as connection:
                # 删除触发器
                connection.execute(text("DROP TRIGGER IF EXISTS trigger_update_calendar_records_updated_at ON public.calendar_records;"))
                
                # 删除触发器函数
                connection.execute(text("DROP FUNCTION IF EXISTS update_calendar_records_updated_at();"))
                
                # 删除表
                connection.execute(text("DROP TABLE IF EXISTS public.calendar_records CASCADE;"))
                
                connection.commit()
            
            logger.info("日历内容记录表删除成功")
            return True
            
    except Exception as e:
        logger.error(f"删除日历内容记录表失败: {str(e)}", exc_info=True)
        return False


def main():
    """
    主函数
    """
    if len(sys.argv) != 2:
        print("使用方法:")
        print("  python create_calendar_records_table.py create   # 创建表")
        print("  python create_calendar_records_table.py check    # 检查表")
        print("  python create_calendar_records_table.py drop     # 删除表")
        sys.exit(1)
    
    action = sys.argv[1].lower()
    
    if action == 'create':
        success = create_calendar_records_table()
        if success:
            print("✅ 日历内容记录表创建成功")
        else:
            print("❌ 日历内容记录表创建失败")
            sys.exit(1)
            
    elif action == 'check':
        exists = check_calendar_records_table()
        if exists:
            print("✅ 日历内容记录表存在")
        else:
            print("❌ 日历内容记录表不存在")
            
    elif action == 'drop':
        success = drop_calendar_records_table()
        if success:
            print("✅ 日历内容记录表删除成功")
        else:
            print("❌ 日历内容记录表删除失败")
            sys.exit(1)
            
    else:
        print(f"未知操作: {action}")
        print("支持的操作: create, check, drop")
        sys.exit(1)


if __name__ == '__main__':
    main()
