# -*- coding: utf-8 -*-
"""Seed default permissions and role-permission bindings into existing DB."""
import sqlite3
from datetime import datetime

DB_PATH = 'data/user_management.db'
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()

permissions = [
    ('User List',     'user:list',               2, 'List users',         '/api/v1/users',                'GET',    10),
    ('View User',     'user:view',               2, 'View user detail',    '/api/v1/users/:id',            'GET',    11),
    ('Edit User',     'user:edit',               2, 'Edit user info',      '/api/v1/users/:id',            'PUT',    12),
    ('Delete User',   'user:delete',             2, 'Delete user',         '/api/v1/users/:id',            'DELETE', 13),
    ('Manage User',   'user:manage',             2, 'Manage user status',  '/api/v1/users/:id/status',     'PUT',    14),
    ('View Profile',  'profile:view',            2, 'View own profile',    '/api/v1/auth/userinfo',        'GET',    20),
    ('Edit Profile',  'profile:edit',            2, 'Edit own profile',    '/api/v1/users/:id',            'PUT',    21),
    ('Change Pwd',    'profile:change_password', 2, 'Change password',     '/api/v1/users/:id/password',   'PUT',    22),
    ('Role Manage',   'role:manage',             2, 'Manage roles',        '/api/v1/roles',                'GET',    30),
    ('Create Role',   'role:create',             2, 'Create role',         '/api/v1/roles',                'POST',   31),
    ('Edit Role',     'role:edit',               2, 'Edit role',           '/api/v1/roles/:id',            'PUT',    32),
    ('Delete Role',   'role:delete',             2, 'Delete role',         '/api/v1/roles/:id',            'DELETE', 33),
    ('Perm Manage',   'permission:manage',       2, 'Manage permissions',  '/api/v1/permissions',          'GET',    40),
    ('View Own Log',  'log:view_own',            2, 'View own login log',  '/api/v1/logs/login/me',        'GET',    50),
    ('View All Logs', 'log:view_all',            2, 'View all logs (admin)','/api/v1/logs/login',          'GET',    51),
    ('Dashboard',     'stats:view',              2, 'View dashboard stats','/api/v1/admin/stats/dashboard','GET',    60),
    ('Device Manage', 'device:manage',           2, 'Manage devices',      '/api/v1/devices',              'GET',    70),
]

now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
perm_ids = {}

for name, code, ptype, desc, path, method, sort in permissions:
    cur.execute('SELECT id FROM permissions WHERE code=?', (code,))
    row = cur.fetchone()
    if row:
        perm_ids[code] = row[0]
        print(f'  skip existing: {code}')
    else:
        cur.execute(
            'INSERT INTO permissions(name,code,type,description,level,path,method,sort,status,created_at,updated_at) VALUES(?,?,?,?,1,?,?,?,1,?,?)',
            (name, code, ptype, desc, path, method, sort, now, now)
        )
        perm_ids[code] = cur.lastrowid
        print(f'  created: {code}')

conn.commit()

# Admin role: bind all permissions
cur.execute('SELECT id FROM roles WHERE code=?', ('admin',))
admin_role = cur.fetchone()
if admin_role:
    rid = admin_role[0]
    for code, pid in perm_ids.items():
        cur.execute('SELECT 1 FROM role_permissions WHERE role_id=? AND permission_id=?', (rid, pid))
        if not cur.fetchone():
            cur.execute('INSERT INTO role_permissions(role_id,permission_id) VALUES(?,?)', (rid, pid))
    conn.commit()
    print(f'Admin role {rid}: bound {len(perm_ids)} permissions')

# User role: bind basic permissions
cur.execute('SELECT id FROM roles WHERE code=?', ('user',))
user_role = cur.fetchone()
if user_role:
    rid = user_role[0]
    for code in ['profile:view', 'profile:edit', 'log:view_own']:
        pid = perm_ids.get(code)
        if pid:
            cur.execute('SELECT 1 FROM role_permissions WHERE role_id=? AND permission_id=?', (rid, pid))
            if not cur.fetchone():
                cur.execute('INSERT INTO role_permissions(role_id,permission_id) VALUES(?,?)', (rid, pid))
    conn.commit()
    print(f'User role {rid}: bound 3 base permissions')

# Summary
cur.execute('SELECT COUNT(*) FROM permissions')
print(f'\nTotal permissions: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM role_permissions')
print(f'Total role_permissions: {cur.fetchone()[0]}')

conn.close()
print('Done.')
