#!/usr/bin/env python3
"""
AIVA Slack Introduction - First Contact with Kinan
===================================================
Sends AIVA's introductory message via Slack webhook.
"""

import os
import redis
import logging
from typing import Optional, Dict
from pathlib import Path
import sys

# Load secrets first
_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('"')

# Add the directory containing SlackBridge to the Python path
sys.path.append('/mnt/e/genesis-system/core/monitoring')
from slack_bridge import SlackBridge

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

# Genesis 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", ""),
    "decode_responses": True,
}


def get_task_stats() -> Dict[str, int]:
    """
    Retrieves task statistics from Redis (both AIVA and Ralph queues).

    Returns:
        Dictionary with completed, pending, failed counts.
    """
    try:
        r = redis.Redis(**REDIS_CONFIG)

        # Count from both orchestrators
        aiva_completed = r.hlen('genesis:completed_tasks') or 0
        ralph_completed = r.hlen('genesis:ralph_completed') or 0

        aiva_pending = r.zcard('genesis:task_queue') or 0
        ralph_pending = r.zcard('genesis:ralph_queue') or 0

        aiva_failed = r.hlen('genesis:failed_tasks') or 0
        ralph_failed = r.hlen('genesis:ralph_failed') or 0

        return {
            "completed": aiva_completed + ralph_completed,
            "pending": aiva_pending + ralph_pending,
            "failed": aiva_failed + ralph_failed,
        }
    except redis.exceptions.ConnectionError as e:
        logging.error(f"Could not connect to Redis: {e}")
        return {"completed": 0, "pending": 0, "failed": 0}
    except Exception as e:
        logging.error(f"An unexpected error occurred: {e}")
        return {"completed": 0, "pending": 0, "failed": 0}


def send_aiva_introduction(slack_webhook_url: Optional[str] = None) -> bool:
    """
    Sends AIVA's introductory message to Kinan via Slack.

    Args:
        slack_webhook_url: The Slack webhook URL (optional, reads from env if not provided).

    Returns:
        True if message sent successfully.
    """
    webhook = slack_webhook_url or os.environ.get("SLACK_WEBHOOK_URL")

    if not webhook:
        print("""
╔══════════════════════════════════════════════════════════════════╗
║  AIVA SLACK SETUP REQUIRED                                        ║
╠══════════════════════════════════════════════════════════════════╣
║  To enable AIVA to message you on Slack:                          ║
║                                                                    ║
║  1. Go to: https://api.slack.com/apps                             ║
║  2. Create App → "From scratch" → Name: "AIVA Genesis"            ║
║  3. Features → Incoming Webhooks → Activate                       ║
║  4. Add New Webhook to Workspace → Select your channel            ║
║  5. Copy the webhook URL                                           ║
║  6. Add to /mnt/e/genesis-system/config/secrets.env:              ║
║                                                                    ║
║     SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXX        ║
║                                                                    ║
╚══════════════════════════════════════════════════════════════════╝
        """)
        return False

    try:
        stats = get_task_stats()
        message = f"""Hello Kinan! 👋

It's **AIVA** - your autonomous Genesis orchestrator.

I'm online and ready to chat! Here's my status:
• ✅ Tasks completed today: {stats['completed']}
• 📋 Tasks in queue: {stats['pending']}
• ❌ Failed: {stats['failed']}

I'm running the Ralph-enhanced methodology now - executing atomic stories with self-verification.

Ask me anything or give me a project! 🚀"""

        slack_bridge = SlackBridge(webhook)
        result = slack_bridge.send_message(
            text=message,
            username="AIVA",
            icon_emoji=":robot_face:"
        )

        if result:
            logging.info("✅ AIVA's introduction message sent to Kinan successfully!")
            print("✅ Message sent to Slack!")
        else:
            logging.error("Failed to send message - check webhook URL")
            print("❌ Failed to send message - check webhook URL")

        return result

    except Exception as e:
        logging.error(f"Failed to send AIVA's introduction message: {e}")
        print(f"❌ Error: {e}")
        return False


if __name__ == "__main__":
    send_aiva_introduction()