#!/usr/bin/env python3
"""
初始化角色系统默认数据

运行方式：
    cd backend
    python scripts/init_roles.py
"""

import sys
import os

# 添加 backend 目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session

from app.config import settings
from app.models import Role


def init_roles():
    """初始化三个默认角色：user / agent / admin"""
    
    # 使用配置中的数据库 URL
    # 注意：本地开发使用 aiosqlite 异步驱动，但脚本是同步的
    # 需要将 sqlite+aiosqlite:// 替换为 sqlite://
    db_url = settings.database_url.replace("sqlite+aiosqlite://", "sqlite://")
    engine = create_engine(db_url)
    
    with Session(engine) as session:
        # 检查是否已有角色数据
        existing = session.execute(select(Role)).scalars().all()
        if existing:
            print(f"角色表已有 {len(existing)} 条数据，跳过初始化")
            for role in existing:
                print(f"  - {role.name}: {role.display_name} (is_default={role.is_default})")
            return
        
        # 创建默认角色
        roles = [
            Role(
                name="user",
                display_name="用户",
                description="所有在职员工默认角色，可提交工单、查看知识库、与 AI 对话",
                permissions=["submit_ticket", "view_knowledge", "chat_with_ai", "view_own_tickets"],
                is_default=True,
            ),
            Role(
                name="agent",
                display_name="坐席",
                description="IT 坐席人员，可处理工单、查看所有会话、使用坐席工具",
                permissions=[
                    "submit_ticket", "view_knowledge", "chat_with_ai", "view_own_tickets",
                    "handle_tickets", "view_all_conversations", "use_agent_tools",
                    "transfer_conversations", "manage_quick_replies",
                ],
                is_default=False,
            ),
            Role(
                name="admin",
                display_name="管理员",
                description="系统管理员，可管理所有配置、用户、角色和数据",
                permissions=[
                    "submit_ticket", "view_knowledge", "chat_with_ai", "view_own_tickets",
                    "handle_tickets", "view_all_conversations", "use_agent_tools",
                    "transfer_conversations", "manage_quick_replies",
                    "manage_users", "manage_roles", "manage_system_config",
                    "view_analytics", "manage_knowledge_base",
                ],
                is_default=False,
            ),
        ]
        
        session.add_all(roles)
        session.commit()
        
        print("[OK] 角色初始化完成：")
        for role in roles:
            print(f"  - {role.name}: {role.display_name}")


if __name__ == "__main__":
    init_roles()
