#!/usr/bin/env python3
"""
Initialize default log settings in database.

Run this script to create default logging configuration settings.
"""

# Register all models with SQLAlchemy so string-based relationships resolve
import contextlib

for _mod in [
    "app.modules.billing.models",
    "app.modules.inventory.models",
    "app.modules.cart.models",
    "app.modules.messaging.models",
    "app.modules.loyalty.models",
    "app.modules.catalog.models",
    "app.modules.customers.models",
    "app.modules.orders.models",
    "app.modules.marketplace.models",
    "app.modules.cms.models",
]:
    with contextlib.suppress(ImportError):
        __import__(_mod)

from app.core.database import SessionLocal
from app.modules.tenancy.models import AdminSetting


def init_log_settings():
    """Create default log settings if they don't exist."""
    db = SessionLocal()

    try:
        settings_to_create = [
            {
                "key": "log_level",
                "value": "INFO",
                "value_type": "string",
                "category": "logging",
                "description": "Application log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)",
                "is_public": False,
                "is_encrypted": False,
            },
            {
                "key": "log_file_max_size_mb",
                "value": "10",
                "value_type": "integer",
                "category": "logging",
                "description": "Maximum log file size in MB before rotation",
                "is_public": False,
                "is_encrypted": False,
            },
            {
                "key": "log_file_backup_count",
                "value": "5",
                "value_type": "integer",
                "category": "logging",
                "description": "Number of rotated log files to keep",
                "is_public": False,
                "is_encrypted": False,
            },
            {
                "key": "db_log_retention_days",
                "value": "30",
                "value_type": "integer",
                "category": "logging",
                "description": "Number of days to retain logs in database",
                "is_public": False,
                "is_encrypted": False,
            },
            {
                "key": "file_logging_enabled",
                "value": "true",
                "value_type": "boolean",
                "category": "logging",
                "description": "Enable file-based logging",
                "is_public": False,
                "is_encrypted": False,
            },
            {
                "key": "db_logging_enabled",
                "value": "true",
                "value_type": "boolean",
                "category": "logging",
                "description": "Enable database logging for critical events",
                "is_public": False,
                "is_encrypted": False,
            },
        ]

        created_count = 0
        updated_count = 0

        for setting_data in settings_to_create:
            existing = (
                db.query(AdminSetting)
                .filter(AdminSetting.key == setting_data["key"])
                .first()
            )

            if existing:
                print(
                    f"✓ Setting '{setting_data['key']}' already exists (value: {existing.value})"
                )
                updated_count += 1
            else:
                setting = AdminSetting(**setting_data)
                db.add(setting)  # noqa: PERF006
                created_count += 1
                print(
                    f"✓ Created setting '{setting_data['key']}' = {setting_data['value']}"
                )

        db.commit()

        print("\n" + "=" * 70)
        print("LOG SETTINGS INITIALIZATION COMPLETE")
        print("=" * 70)
        print(f"  Created: {created_count} settings")
        print(f"  Existing: {updated_count} settings")
        print(f"  Total: {len(settings_to_create)} settings")
        print("=" * 70)

    except Exception as e:
        db.rollback()
        print(f"Error initializing log settings: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    print("=" * 70)
    print("INITIALIZING LOG SETTINGS")
    print("=" * 70)
    init_log_settings()
