"""
简单的初始化脚本
"""
import sqlite3
import os

# 创建数据库文件
db_path = 'kaopeilian.db'

# 如果数据库已存在，删除它
if os.path.exists(db_path):
    os.remove(db_path)

# 连接数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

# 创建teams表
cursor.execute('''
CREATE TABLE IF NOT EXISTS teams (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR(100) NOT NULL UNIQUE,
    code VARCHAR(50) NOT NULL UNIQUE,
    description TEXT,
    team_type VARCHAR(50) DEFAULT 'department',
    is_active BOOLEAN DEFAULT 1,
    leader_id INTEGER,
    parent_id INTEGER,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_deleted BOOLEAN DEFAULT 0,
    deleted_at DATETIME,
    created_by INTEGER,
    updated_by INTEGER,
    FOREIGN KEY (parent_id) REFERENCES teams(id),
    FOREIGN KEY (leader_id) REFERENCES users(id)
)
''')

# 创建users表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL UNIQUE,
    phone VARCHAR(20) UNIQUE,
    hashed_password VARCHAR(200) NOT NULL,
    full_name VARCHAR(100),
    avatar_url VARCHAR(500),
    bio TEXT,
    role VARCHAR(20) DEFAULT 'trainee',
    is_active BOOLEAN DEFAULT 1,
    is_verified BOOLEAN DEFAULT 0,
    last_login_at DATETIME,
    password_changed_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_deleted BOOLEAN DEFAULT 0,
    deleted_at DATETIME,
    created_by INTEGER,
    updated_by INTEGER
)
''')

# 创建user_teams关联表
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_teams (
    user_id INTEGER NOT NULL,
    team_id INTEGER NOT NULL,
    role VARCHAR(50) DEFAULT 'member',
    joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id, team_id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (team_id) REFERENCES teams(id)
)
''')

# 提交更改
conn.commit()
conn.close()

print("✓ SQLite数据库初始化成功！")
print(f"✓ 数据库文件: {os.path.abspath(db_path)}")
