import json
import os
import logging
import requests
from typing import Optional, Dict

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def find_slack_credentials(n8n_workflow_path: str) -> Optional[Dict[str, str]]:
    """
    Analyzes n8n workflow files to identify Slack credentials and webhook URLs.

    Args:
        n8n_workflow_path: The directory containing the n8n workflow files.

    Returns:
        A dictionary containing the Slack credentials and webhook URL, or None if not found.
    """
    slack_credentials = {}
    for filename in os.listdir(n8n_workflow_path):
        if filename.endswith(".json"):
            filepath = os.path.join(n8n_workflow_path, filename)
            try:
                with open(filepath, "r") as f:
                    workflow_data = json.load(f)
                    # This is a placeholder - needs actual logic to traverse the n8n workflow JSON structure
                    # to find the slack credentials. Assuming they are in a node named 'Slack'
                    # and the credentials are named 'accessToken' and 'webhookUrl'
                    nodes = workflow_data.get('nodes', [])
                    for node in nodes:
                        if node.get('type') == 'Slack':
                            credentials = node.get('credentials', {})
                            slack_credentials['accessToken'] = credentials.get('accessToken')
                            slack_credentials['webhookUrl'] = node.get('parameters', {}).get('webhookUrl')  # Assuming webhook URL is a node parameter
                            if slack_credentials.get('accessToken') and slack_credentials.get('webhookUrl'):
                                logging.info(f"Slack credentials found in {filename}")
                                return slack_credentials
            except FileNotFoundError:
                logging.error(f"File not found: {filepath}")
            except json.JSONDecodeError:
                logging.error(f"Invalid JSON in file: {filepath}")
            except Exception as e:
                logging.error(f"Error processing file {filepath}: {e}")
    logging.warning("Slack credentials not found in any n8n workflow file.")
    return None


def send_slack_message(webhook_url: str, message: str) -> bool:
    """
    Sends a message to a Slack channel using a webhook URL.

    Args:
        webhook_url: The Slack webhook URL.
        message: The message to send.

    Returns:
        True if the message was sent successfully, False otherwise.
    """
    try:
        data = {"text": message}
        response = requests.post(webhook_url, json=data)
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
        logging.info("Message sent successfully to Slack.")
        return True
    except requests.exceptions.RequestException as e:
        logging.error(f"Error sending message to Slack: {e}")
        return False


def main():
    """
    Main function to find Slack credentials and send a test message.
    """
    n8n_workflow_path = "/mnt/e/genesis-system/config/n8n/"
    slack_credentials = find_slack_credentials(n8n_workflow_path)

    if slack_credentials:
        webhook_url = slack_credentials.get('webhookUrl')
        if webhook_url:
            message = "Hello Kinan, this is AIVA testing the Slack integration via n8n."
            send_slack_message(webhook_url, message)
        else:
            logging.error("Webhook URL not found.")
    else:
        logging.error("Slack credentials not found.")


if __name__ == "__main__":
    main()