"""
数据库迁移脚本 - v2.4.0
为Tag模型添加SEO相关字段

新增字段:
- seo_title: SEO标题
- seo_description: SEO页面描述
- seo_keywords: SEO关键词

使用方法:
python migrate_tag_seo_fields.py
"""

import os
import sys
from sqlalchemy import text

# 添加项目根目录到sys.path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import create_app
from models import db

def migrate_tag_seo_fields():
    """为Tag表添加SEO字段"""
    app = create_app(os.getenv('FLASK_ENV', 'production'))

    with app.app_context():
        print("开始迁移Tag表，添加SEO字段...")

        try:
            # 检查字段是否已存在
            inspector = db.inspect(db.engine)
            columns = [col['name'] for col in inspector.get_columns('tags')]

            # 添加seo_title字段
            if 'seo_title' not in columns:
                print("添加字段: seo_title")
                db.session.execute(text(
                    "ALTER TABLE tags ADD COLUMN seo_title VARCHAR(100) COMMENT 'SEO标题(v2.4新增)'"
                ))
                print("[OK] seo_title 字段添加成功")
            else:
                print("[SKIP] seo_title 字段已存在，跳过")

            # 添加seo_description字段
            if 'seo_description' not in columns:
                print("添加字段: seo_description")
                db.session.execute(text(
                    "ALTER TABLE tags ADD COLUMN seo_description VARCHAR(300) COMMENT 'SEO页面描述(v2.4新增)'"
                ))
                print("[OK] seo_description 字段添加成功")
            else:
                print("[SKIP] seo_description 字段已存在，跳过")

            # 添加seo_keywords字段
            if 'seo_keywords' not in columns:
                print("添加字段: seo_keywords")
                db.session.execute(text(
                    "ALTER TABLE tags ADD COLUMN seo_keywords VARCHAR(200) COMMENT 'SEO关键词(v2.4新增)'"
                ))
                print("[OK] seo_keywords 字段添加成功")
            else:
                print("[SKIP] seo_keywords 字段���存在，跳过")

            # 提交更改
            db.session.commit()
            print("\n[SUCCESS] 数据库迁移完成!")
            print("\n建议：登录后台管理系统，为每个标签填写SEO信息，以提升搜索引擎排名。")

        except Exception as e:
            db.session.rollback()
            print(f"\n[ERROR] 迁移失败: {str(e)}")
            raise
        finally:
            db.session.close()

if __name__ == '__main__':
    migrate_tag_seo_fields()
