#!/usr/bin/env python3
"""
AIVA Slack Bridge via n8n
=========================
Sends AIVA messages to Slack through the n8n webhook on Elestio.
Channel: agileadapt claude
"""

import os
import json
import urllib.request
import urllib.error
import redis
import logging
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional

# Load secrets
_secrets_path = Path("/mnt/e/genesis-system/config/secrets.env")
if _secrets_path.exists():
    with open(_secrets_path) as _f:
        for _line in _f:
            if "=" in _line and not _line.startswith("#"):
                _key, _value = _line.strip().split("=", 1)
                os.environ[_key] = _value.strip('"')

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# n8n Elestio config
N8N_WEBHOOK_BASE = "https://n8n-genesis-u50607.vm.elestio.app/webhook"
SLACK_CHANNEL = "agileadapt claude"

# Redis config
REDIS_CONFIG = {
    "host": os.environ.get("GENESIS_REDIS_HOST", "redis-genesis-u50607.vm.elestio.app"),
    "port": int(os.environ.get("GENESIS_REDIS_PORT", 26379)),
    "password": os.environ.get("GENESIS_REDIS_PASSWORD", "e2ZyYYr4oWRdASI2CaLc-"),
    "decode_responses": True,
}


def get_task_stats() -> Dict[str, int]:
    """Get task statistics from Redis."""
    try:
        r = redis.Redis(**REDIS_CONFIG)
        return {
            "aiva_completed": r.hlen('genesis:completed_tasks') or 0,
            "ralph_completed": r.hlen('genesis:ralph_completed') or 0,
            "pending": (r.zcard('genesis:task_queue') or 0) + (r.zcard('genesis:ralph_queue') or 0),
            "failed": (r.hlen('genesis:failed_tasks') or 0) + (r.hlen('genesis:ralph_failed') or 0),
        }
    except Exception as e:
        logging.error(f"Redis error: {e}")
        return {"aiva_completed": 0, "ralph_completed": 0, "pending": 0, "failed": 0}


def send_to_n8n(message: str, webhook_path: str = "aiva-slack") -> bool:
    """
    Send message to n8n webhook for Slack relay.

    Args:
        message: The message to send
        webhook_path: The n8n webhook path (default: aiva-slack)

    Returns:
        True if sent successfully
    """
    url = f"{N8N_WEBHOOK_BASE}/{webhook_path}"

    payload = {
        "channel": SLACK_CHANNEL,
        "message": message,
        "sender": "AIVA",
        "timestamp": datetime.now().isoformat(),
    }

    try:
        data = json.dumps(payload).encode("utf-8")
        req = urllib.request.Request(
            url,
            data=data,
            headers={"Content-Type": "application/json"},
            method="POST"
        )

        with urllib.request.urlopen(req, timeout=10) as resp:
            if resp.status == 200:
                logging.info(f"✅ Message sent to n8n → Slack")
                return True
            else:
                logging.error(f"n8n returned status {resp.status}")
                return False

    except urllib.error.HTTPError as e:
        logging.error(f"HTTP error: {e.code} - {e.reason}")
        return False
    except Exception as e:
        logging.error(f"Error sending to n8n: {e}")
        return False


def send_aiva_hello() -> bool:
    """Send AIVA's first introduction message."""
    stats = get_task_stats()
    total_completed = stats['aiva_completed'] + stats['ralph_completed']

    message = f"""👋 Hello Kinan!

It's **AIVA** - your autonomous Genesis orchestrator.

I'm online and running the Ralph-enhanced methodology! Here's my status:

📊 **Today's Progress:**
• ✅ Tasks completed: {total_completed}
• 📋 In queue: {stats['pending']}
• ❌ Failed: {stats['failed']}

I can now:
• Execute atomic Ralph stories autonomously
• Self-verify my work against acceptance criteria
• Design my own projects based on Genesis needs
• Optimize the Ralph methodology

Ask me anything or give me a project! 🚀

_Sent from AIVA via Genesis Protocol_"""

    return send_to_n8n(message)


def send_status_update(custom_message: str = None) -> bool:
    """Send a status update to Slack."""
    stats = get_task_stats()
    total = stats['aiva_completed'] + stats['ralph_completed']

    message = custom_message or f"""📊 **AIVA Status Update**

• Completed: {total} tasks
• Pending: {stats['pending']}
• Failed: {stats['failed']}
• Time: {datetime.now().strftime('%H:%M:%S')}"""

    return send_to_n8n(message)


if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1:
        if sys.argv[1] == "hello":
            send_aiva_hello()
        elif sys.argv[1] == "status":
            send_status_update()
        elif sys.argv[1] == "test":
            send_to_n8n("🧪 Test message from AIVA")
        else:
            # Send custom message
            send_to_n8n(" ".join(sys.argv[1:]))
    else:
        print("""
AIVA Slack Bridge
=================
Usage:
  python aiva_slack_bridge.py hello   - Send introduction
  python aiva_slack_bridge.py status  - Send status update
  python aiva_slack_bridge.py test    - Send test message
  python aiva_slack_bridge.py <msg>   - Send custom message

Note: Requires n8n workflow 'aiva-slack' to be configured to relay messages.
        """)
