#!/usr/bin/env python3
import os
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))

os.environ['USE_POSTGRES'] = 'true'
os.environ['PG_HOST'] = '127.0.0.1'
os.environ['PG_PORT'] = '5432'
os.environ['PG_DATABASE'] = 'yzr_nr'
os.environ['PG_USER'] = 'yzr_nr'
os.environ['PG_PASSWORD'] = 'aTX3WKKnPfRnM5PC'

from app.database import engine, Base, SessionLocal
from app.models import (
    TopicField, TopicConfigField, TopicStatusConfig,
    Topic, Article, PublishRecord, User, Case, TaskLog,
    LLMConfig, SystemConfig, AuditLog,
    ContentCalendar, ContentMetrics, MediaAsset,
    PlatformConfig, ContentTask
)


def migrate():
    print("Creating new tables in PostgreSQL...")
    Base.metadata.create_all(bind=engine)
    print("✅ 所有表已创建/同步")

    db = SessionLocal()
    try:
        if db.query(TopicField).count() == 0:
            fields = [
                {"name": "未来工作方式", "icon": "💼", "color": "#667eea", "description": "远程工作、零工经济、职业转型", "sort_order": 1},
                {"name": "AI与效率", "icon": "🤖", "color": "#764ba2", "description": "AI工具、数字助手、效率方法", "sort_order": 2},
                {"name": "可持续生活", "icon": "🌿", "color": "#67c23a", "description": "环保、低碳、自然生活方式", "sort_order": 3},
                {"name": "数字游民", "icon": "🌍", "color": "#409eff", "description": "旅行、地理自由、海外生活", "sort_order": 4},
                {"name": "个人成长", "icon": "📚", "color": "#e6a23c", "description": "学习、技能、认知升级", "sort_order": 5},
                {"name": "科技人文", "icon": "🔬", "color": "#f56c6c", "description": "科技伦理、数字生活反思", "sort_order": 6},
            ]
            for f in fields:
                db.add(TopicField(**f))
            db.commit()
            print("✅ 插入默认领域")

        if db.query(TopicStatusConfig).count() == 0:
            statuses = [
                {"status": "pending", "label": "待处理", "color": "#E6A23C", "icon": "⏳", "sort_order": 1, "is_default": True},
                {"status": "review", "label": "待审查", "color": "#F56C6C", "icon": "🔍", "sort_order": 2},
                {"status": "draft", "label": "草稿", "color": "#909399", "icon": "📝", "sort_order": 3},
                {"status": "ready", "label": "待发布", "color": "#67C23A", "icon": "✅", "sort_order": 4},
                {"status": "published", "label": "已发布", "color": "#409EFF", "icon": "🚀", "sort_order": 5},
            ]
            for s in statuses:
                db.add(TopicStatusConfig(**s))
            db.commit()
            print("✅ 插入状态配置")

        if db.query(PlatformConfig).count() == 0:
            platforms = [
                {"platform": "zhihu", "name": "知乎", "icon": "🔍",
                 "default_format": "长文深度分析，1500-3000字，有数据支撑",
                 "compliance_rules": {"max_length": 50000, "requires_authentication": False}, "is_active": True},
                {"platform": "wechat", "name": "微信公众号", "icon": "💚",
                 "default_format": "公众号图文，800-1500字，亲切口语化",
                 "compliance_rules": {"max_length": 20000, "requires_authentication": True}, "is_active": True},
                {"platform": "xiaohongshu", "name": "小红书", "icon": "📕",
                 "default_format": "图文笔记，300-800字，emoji+标签",
                 "compliance_rules": {"max_length": 1000, "requires_tags": True, "max_tags": 10}, "is_active": True},
            ]
            for p in platforms:
                db.add(PlatformConfig(**p))
            db.commit()
            print("✅ 插入平台配置")

        existing_fields = {f.name: f.id for f in db.query(TopicField).all()}

        if db.query(Topic).count() == 0:
            import json
            PROJECT_ROOT = Path(__file__).parent.parent
            TOPICS_FILE = PROJECT_ROOT / "automation" / "data" / "sustainability_topics.json"
            if os.path.exists(TOPICS_FILE):
                topics = json.loads(open(TOPICS_FILE, encoding='utf-8').read())
                seen = {}
                for t in topics:
                    seen[t['id']] = t
                for t in list(seen.values()):
                    field_id = existing_fields.get(t.get('field'))
                    topic = Topic(
                        id=t['id'],
                        field_id=field_id,
                        field_name=t.get('field'),
                        title=t['title'],
                        format=t.get('format'),
                        core_concept=t.get('core_concept'),
                        audience_pain=t.get('audience_pain'),
                        unique_angle=t.get('unique_angle'),
                        priority=t.get('priority'),
                        priority_score=t.get('priority_score', 0),
                        total_score=t.get('total_score'),
                        status=t.get('status', 'pending'),
                        cases=t.get('cases', []),
                        tags=t.get('tags', []),
                        ready_at=None,
                        published_at=None,
                        compliance_score=t.get('compliance_score'),
                        platform_urls=t.get('platform_urls', {})
                    )
                    db.add(topic)
                db.commit()
                print(f"✅ 迁移 {len(seen)} 个选题")
            else:
                print(f"⚠️ 选题文件不存在: {TOPICS_FILE}")
        else:
            print("✅ 选题已存在，跳过迁移")

        import bcrypt
        if db.query(User).count() == 0:
            hashed = bcrypt.hashpw("admin123".encode('utf-8'), bcrypt.gensalt())
            admin = User(username="admin", password_hash=hashed.decode('utf-8'), role="admin")
            db.add(admin)
            db.commit()
            print("✅ 创建默认管理员")

        print("\n🎉 迁移完成！PostgreSQL 数据库已就绪。")
        print("运行: cd platform/backend && python -m uvicorn app.main:app --port 8001 --reload")

    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"迁移失败: {e}")
    finally:
        db.close()


if __name__ == "__main__":
    migrate()