"""
Wazuh Configuration Management.

Stores Wazuh connection settings with encrypted credentials.
"""
import json
from typing import Optional, Dict, Any
from pathlib import Path
from souleyez.storage.database import get_db
from souleyez.storage.crypto import get_crypto_manager


class WazuhConfig:
    """Manage Wazuh connection configuration."""

    @staticmethod
    def get_config(engagement_id: int) -> Optional[Dict[str, Any]]:
        """
        Get Wazuh config for an engagement.

        Returns:
            Config dict or None if not configured
        """
        db = get_db()
        conn = db.get_connection()
        cursor = conn.cursor()

        cursor.execute("""
            SELECT api_url, api_user, api_password, indexer_url, indexer_user, indexer_password, verify_ssl, enabled
            FROM wazuh_config
            WHERE engagement_id = ?
        """, (engagement_id,))

        row = cursor.fetchone()
        if not row:
            return None

        # Decrypt passwords
        api_password = row[2]
        indexer_password = row[5]
        try:
            crypto = get_crypto_manager()
            if crypto:
                if api_password:
                    api_password = crypto.decrypt(api_password)
                if indexer_password:
                    indexer_password = crypto.decrypt(indexer_password)
        except Exception:
            pass  # Return encrypted if decryption fails

        return {
            "api_url": row[0],
            "api_user": row[1],
            "api_password": api_password,
            "indexer_url": row[3],
            "indexer_user": row[4] or "admin",
            "indexer_password": indexer_password,
            "verify_ssl": bool(row[6]),
            "enabled": bool(row[7])
        }

    @staticmethod
    def save_config(
        engagement_id: int,
        api_url: str,
        api_user: str,
        api_password: str,
        indexer_url: Optional[str] = None,
        indexer_user: Optional[str] = None,
        indexer_password: Optional[str] = None,
        verify_ssl: bool = False,
        enabled: bool = True
    ) -> bool:
        """
        Save Wazuh config for an engagement.

        Passwords are encrypted before storage.
        """
        db = get_db()
        conn = db.get_connection()
        cursor = conn.cursor()

        # Encrypt passwords
        encrypted_api_password = api_password
        encrypted_indexer_password = indexer_password
        try:
            crypto = get_crypto_manager()
            if crypto:
                encrypted_api_password = crypto.encrypt(api_password)
                if indexer_password:
                    encrypted_indexer_password = crypto.encrypt(indexer_password)
        except Exception:
            pass  # Store plaintext if encryption unavailable

        # Upsert config
        cursor.execute("""
            INSERT INTO wazuh_config (engagement_id, api_url, api_user, api_password, indexer_url, indexer_user, indexer_password, verify_ssl, enabled)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(engagement_id) DO UPDATE SET
                api_url = excluded.api_url,
                api_user = excluded.api_user,
                api_password = excluded.api_password,
                indexer_url = excluded.indexer_url,
                indexer_user = excluded.indexer_user,
                indexer_password = excluded.indexer_password,
                verify_ssl = excluded.verify_ssl,
                enabled = excluded.enabled
        """, (engagement_id, api_url, api_user, encrypted_api_password, indexer_url, indexer_user or 'admin', encrypted_indexer_password, verify_ssl, enabled))

        conn.commit()
        return True

    @staticmethod
    def delete_config(engagement_id: int) -> bool:
        """Delete Wazuh config for an engagement."""
        db = get_db()
        conn = db.get_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM wazuh_config WHERE engagement_id = ?", (engagement_id,))
        conn.commit()
        return cursor.rowcount > 0

    @staticmethod
    def is_configured(engagement_id: int) -> bool:
        """Check if Wazuh is configured for an engagement."""
        config = WazuhConfig.get_config(engagement_id)
        return config is not None and config.get("enabled", False)
