#!/usr/bin/env python
"""
創建示範資料 - ISO 27001 資產盤點系統
"""
import os
import sys
import django
from datetime import date, timedelta
import random

# 設定 Django 環境
sys.path.insert(0, os.path.dirname(__file__))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from accounts.models import User
from assets.models import Asset, AssetRelationship

def create_departments():
    """創建部門資訊（僅作為字串）"""
    print("\n準備部門資料...")
    departments = ['IT部門', '財務部', '人資部', '業務部', '研發部']
    print(f"  ✓ 部門: {', '.join(departments)}")
    return departments

def create_users(departments):
    """創建使用者"""
    print("\n創建使用者資料...")
    users_data = [
        {
            'username': 'admin',
            'email': 'admin@example.com',
            'first_name': '管理員',
            'last_name': '系統',
            'role': 'super_admin',
            'department': departments[0],  # IT部門
        },
        {
            'username': 'security_officer',
            'email': 'security@example.com',
            'first_name': '大華',
            'last_name': '李',
            'role': 'security_officer',
            'department': departments[0],  # IT部門
        },
        {
            'username': 'auditor',
            'email': 'auditor@example.com',
            'first_name': '美麗',
            'last_name': '王',
            'role': 'auditor',
            'department': departments[0],  # IT部門
        },
        {
            'username': 'it_manager',
            'email': 'it@example.com',
            'first_name': '小明',
            'last_name': '張',
            'role': 'org_admin',
            'department': departments[0],  # IT部門
        },
        {
            'username': 'hr_staff',
            'email': 'hr@example.com',
            'first_name': '小芳',
            'last_name': '陳',
            'role': 'employee',
            'department': departments[2],  # 人資部
        },
    ]
    
    users = []
    for user_data in users_data:
        user, created = User.objects.get_or_create(
            username=user_data['username'],
            defaults={
                'email': user_data['email'],
                'first_name': user_data['first_name'],
                'last_name': user_data['last_name'],
                'role': user_data['role'],
                'department': user_data['department'],
            }
        )
        if created:
            user.set_password('demo1234')  # 設定預設密碼
            user.save()
            print(f"  ✓ 使用者已建立: {user.get_full_name()} ({user.username}) - 密碼: demo1234")
        else:
            print(f"  ℹ 使用者已存在: {user.get_full_name()}")
        users.append(user)
    
    return users

def create_hardware_assets(users):
    """創建硬體資產"""
    print("\n創建硬體資產...")
    hardware_assets = [
        {
            'asset_number': 'HW-SRV-001',
            'name': 'Web Application Server',
            'description': '主要網站應用伺服器 - Ubuntu 22.04',
            'asset_subtype': 'server',
            'location': '機房A - Rack 01 - U1-4',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'os': 'Ubuntu 22.04 LTS',
                'cpu': 'Intel Xeon 8 cores',
                'ram': '64GB DDR4',
                'storage': '2TB SSD RAID 1',
                'ip': '192.168.1.10',
            }
        },
        {
            'asset_number': 'HW-SRV-002',
            'name': 'Database Server',
            'description': 'PostgreSQL 主資料庫伺服器',
            'asset_subtype': 'server',
            'location': '機房A - Rack 01 - U5-8',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'os': 'Ubuntu 22.04 LTS',
                'cpu': 'Intel Xeon 16 cores',
                'ram': '128GB DDR4',
                'storage': '4TB SSD RAID 10',
                'ip': '192.168.1.11',
            }
        },
        {
            'asset_number': 'HW-SRV-003',
            'name': 'Backup Server',
            'description': '備份伺服器 - Veeam',
            'asset_subtype': 'server',
            'location': '機房B - Rack 05 - U1-4',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'medium',
            'technical_details': {
                'os': 'Windows Server 2022',
                'cpu': 'Intel Xeon 8 cores',
                'ram': '32GB DDR4',
                'storage': '10TB HDD RAID 6',
                'ip': '192.168.2.10',
            }
        },
        {
            'asset_number': 'HW-NET-001',
            'name': 'Core Switch',
            'description': '核心交換器 - Cisco Catalyst',
            'asset_subtype': 'network_device',
            'location': '機房A - Rack 03 - U20',
            'confidentiality': 'medium',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'model': 'Cisco Catalyst 9300',
                'ports': '48 x 1GbE + 4 x 10GbE SFP+',
                'firmware': 'IOS XE 17.6.3',
                'ip': '192.168.1.1',
            }
        },
        {
            'asset_number': 'HW-NET-002',
            'name': 'Firewall',
            'description': '防火牆 - FortiGate',
            'asset_subtype': 'network_device',
            'location': '機房A - Rack 03 - U21',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'model': 'FortiGate 600E',
                'throughput': '10 Gbps',
                'firmware': 'FortiOS 7.2.4',
                'wan_ip': '203.123.45.1',
            }
        },
        {
            'asset_number': 'HW-STG-001',
            'name': 'NAS Storage',
            'description': 'Synology NAS - 檔案伺服器',
            'asset_subtype': 'storage',
            'location': '機房A - Rack 02 - U10-13',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'medium',
            'technical_details': {
                'model': 'Synology RS3621xs+',
                'capacity': '48TB (RAID 6)',
                'disks': '12 x 4TB SSD',
                'ip': '192.168.1.20',
            }
        },
        {
            'asset_number': 'HW-PC-001',
            'name': '財務部主管電腦',
            'description': 'Dell OptiPlex 工作站',
            'asset_subtype': 'workstation',
            'location': '辦公室 3F - 財務部',
            'confidentiality': 'high',
            'integrity': 'medium',
            'availability': 'medium',
            'technical_details': {
                'model': 'Dell OptiPlex 7090',
                'os': 'Windows 11 Pro',
                'cpu': 'Intel Core i7',
                'ram': '16GB',
                'storage': '512GB SSD',
            }
        },
    ]
    
    assets = []
    for asset_data in hardware_assets:
        asset, created = Asset.objects.get_or_create(
            asset_number=asset_data['asset_number'],
            defaults={
                **asset_data,
                'asset_type': 'hardware',
                'owner': random.choice(users),
                'custodian': random.choice(users),
                'status': 'active',
                'acquisition_date': date.today() - timedelta(days=random.randint(30, 730)),
            }
        )
        assets.append(asset)
        if created:
            print(f"  ✓ {asset.asset_number} - {asset.name}")
    
    return assets

def create_software_assets(users):
    """創建軟體資產"""
    print("\n創建軟體資產...")
    software_assets = [
        {
            'asset_number': 'SW-OS-001',
            'name': 'Windows Server 2022 授權',
            'description': '伺服器作業系統授權 x 5',
            'asset_subtype': 'operating_system',
            'location': '雲端授權管理',
            'confidentiality': 'low',
            'integrity': 'medium',
            'availability': 'high',
            'technical_details': {
                'license_type': 'Volume License',
                'quantity': 5,
                'license_key': 'XXXXX-XXXXX-XXXXX-XXXXX',
                'vendor': 'Microsoft',
                'purchase_date': '2024-01-15',
                'expiry_date': '2026-01-14',
            }
        },
        {
            'asset_number': 'SW-DB-001',
            'name': 'PostgreSQL',
            'description': '開源資料庫系統',
            'asset_subtype': 'database',
            'location': '安裝於 HW-SRV-002',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'version': '15.4',
                'license': 'PostgreSQL License (Open Source)',
                'port': 5432,
            }
        },
        {
            'asset_number': 'SW-APP-001',
            'name': 'Django Framework',
            'description': 'Web 應用程式框架',
            'asset_subtype': 'application',
            'location': '安裝於 HW-SRV-001',
            'confidentiality': 'medium',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'version': '4.2.7',
                'license': 'BSD License (Open Source)',
                'language': 'Python 3.11',
            }
        },
        {
            'asset_number': 'SW-SEC-001',
            'name': 'Kaspersky Endpoint Security',
            'description': '端點防毒軟體 x 50 授權',
            'asset_subtype': 'security',
            'location': '部署於所有工作站',
            'confidentiality': 'low',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'license_count': 50,
                'version': '11.9.0',
                'vendor': 'Kaspersky',
                'renewal_date': '2025-12-31',
            }
        },
        {
            'asset_number': 'SW-OFF-001',
            'name': 'Microsoft 365 商務版',
            'description': 'Office 365 訂閱 x 50 使用者',
            'asset_subtype': 'productivity',
            'location': '雲端服務',
            'confidentiality': 'medium',
            'integrity': 'medium',
            'availability': 'high',
            'technical_details': {
                'license_type': 'Subscription',
                'user_count': 50,
                'tenant_id': 'example.onmicrosoft.com',
                'renewal_date': '2025-06-30',
            }
        },
    ]
    
    assets = []
    for asset_data in software_assets:
        asset, created = Asset.objects.get_or_create(
            asset_number=asset_data['asset_number'],
            defaults={
                **asset_data,
                'asset_type': 'software',
                'owner': random.choice(users),
                'status': 'active',
                'acquisition_date': date.today() - timedelta(days=random.randint(30, 365)),
            }
        )
        assets.append(asset)
        if created:
            print(f"  ✓ {asset.asset_number} - {asset.name}")
    
    return assets

def create_data_assets(users):
    """創建資料資產"""
    print("\n創建資料資產...")
    data_assets = [
        {
            'asset_number': 'DAT-CRM-001',
            'name': '客戶關係管理資料庫',
            'description': '包含客戶聯絡資訊、交易記錄、合約文件',
            'asset_subtype': 'database',
            'location': 'HW-SRV-002 PostgreSQL',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'database_name': 'crm_production',
                'size': '2.5 TB',
                'records': '~500,000 customers',
                'backup_frequency': 'Daily',
                'encryption': 'AES-256',
            }
        },
        {
            'asset_number': 'DAT-FIN-001',
            'name': '財務會計資料',
            'description': '會計帳目、發票、財務報表',
            'asset_subtype': 'financial_data',
            'location': 'HW-SRV-002 PostgreSQL',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'high',
            'technical_details': {
                'database_name': 'finance_db',
                'size': '500 GB',
                'retention_period': '7 years',
                'compliance': 'SOX, GAAP',
            }
        },
        {
            'asset_number': 'DAT-HR-001',
            'name': '人事薪資資料',
            'description': '員工個資、薪資、考核記錄',
            'asset_subtype': 'personal_data',
            'location': 'HW-STG-001 NAS',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'medium',
            'technical_details': {
                'size': '50 GB',
                'employee_count': '~200',
                'compliance': '個資法',
                'access_control': 'Role-based',
            }
        },
        {
            'asset_number': 'DAT-SRC-001',
            'name': '原始程式碼倉庫',
            'description': 'Git 程式碼倉庫',
            'asset_subtype': 'source_code',
            'location': 'GitHub Enterprise',
            'confidentiality': 'high',
            'integrity': 'high',
            'availability': 'medium',
            'technical_details': {
                'repositories': 45,
                'size': '10 GB',
                'version_control': 'Git',
                'backup': 'Daily to HW-STG-001',
            }
        },
    ]
    
    assets = []
    for asset_data in data_assets:
        asset, created = Asset.objects.get_or_create(
            asset_number=asset_data['asset_number'],
            defaults={
                **asset_data,
                'asset_type': 'data',
                'owner': random.choice(users),
                'status': 'active',
            }
        )
        assets.append(asset)
        if created:
            print(f"  ✓ {asset.asset_number} - {asset.name}")
    
    return assets

def create_relationships(all_assets):
    """創建資產關係"""
    print("\n創建資產關係...")
    
    relationships = [
        # Web Server depends on Database Server
        ('HW-SRV-001', 'HW-SRV-002', 'depends_on', 'Web應用依賴資料庫運作'),
        # Web Server depends on Core Switch
        ('HW-SRV-001', 'HW-NET-001', 'connected_to', '透過網路連接'),
        # Database Server depends on Core Switch
        ('HW-SRV-002', 'HW-NET-001', 'connected_to', '透過網路連接'),
        # All servers backed up by Backup Server
        ('HW-SRV-001', 'HW-SRV-003', 'backed_up_by', '每日自動備份'),
        ('HW-SRV-002', 'HW-SRV-003', 'backed_up_by', '每日自動備份'),
        # Database hosts CRM data
        ('DAT-CRM-001', 'HW-SRV-002', 'hosted_on', 'CRM資料儲存於此資料庫'),
        # Software runs on hardware
        ('SW-DB-001', 'HW-SRV-002', 'installed_on', 'PostgreSQL安裝於此伺服器'),
        ('SW-APP-001', 'HW-SRV-001', 'installed_on', 'Django安裝於此伺服器'),
    ]
    
    asset_dict = {asset.asset_number: asset for asset in all_assets}
    
    for from_num, to_num, rel_type, desc in relationships:
        if from_num in asset_dict and to_num in asset_dict:
            rel, created = AssetRelationship.objects.get_or_create(
                from_asset=asset_dict[from_num],
                to_asset=asset_dict[to_num],
                relationship_type=rel_type,
                defaults={'description': desc}
            )
            if created:
                print(f"  ✓ {from_num} --[{rel_type}]--> {to_num}")

def main():
    """主函數"""
    print("=" * 60)
    print("ISO 27001 資產盤點系統 - 示範資料產生器")
    print("=" * 60)
    
    # 創建部門
    departments = create_departments()
    
    # 創建使用者
    users = create_users(departments)
    
    # 創建資產
    hardware = create_hardware_assets(users)
    software = create_software_assets(users)
    data = create_data_assets(users)
    
    all_assets = hardware + software + data
    
    # 創建資產關係
    create_relationships(all_assets)
    
    print("\n" + "=" * 60)
    print("✅ 示範資料創建完成！")
    print("=" * 60)
    print(f"\n統計資訊：")
    print(f"  - 使用者: {User.objects.count()}")
    print(f"  - 資產: {Asset.objects.count()}")
    print(f"  - 資產關係: {AssetRelationship.objects.count()}")
    
    print(f"\n登入資訊：")
    print(f"  管理員帳號: admin / demo1234")
    print(f"  資安主管: security_officer / demo1234")
    print(f"  稽核員: auditor / demo1234")
    print(f"  IT主管: it_manager / demo1234")
    print(f"  人資員工: hr_staff / demo1234")
    
    print(f"\n系統網址：")
    print(f"  前端: http://localhost:3000")
    print(f"  後端 API: http://localhost:8000/api/")
    print(f"  後端 Admin: http://localhost:8000/admin/")

if __name__ == '__main__':
    main()
