import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime
from dotenv import load_dotenv

# Load credentials from .env
load_dotenv()

SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")
SLACK_CHANNEL_ID = os.getenv("SLACK_CHANNEL_ID")
WORKSPACE_ROOT = Path("e:/genesis-system")
STATE_FILE = WORKSPACE_ROOT / "data" / "nomad_bridge_state.json"
VOICE_DIR = WORKSPACE_ROOT / "data" / "nomad_voice_clips"

class SlackNomadBridge:
    def __init__(self):
        self.last_ts = self._load_state()
        VOICE_DIR.mkdir(parents=True, exist_ok=True)

    def _load_state(self):
        if STATE_FILE.exists():
            with open(STATE_FILE, "r") as f:
                return json.load(f).get("last_ts", "0")
        return "0"

    def _save_state(self, ts):
        with open(STATE_FILE, "w") as f:
            json.dump({"last_ts": ts, "updated_at": datetime.now().isoformat()}, f)

    def poll_messages(self):
        if not SLACK_BOT_TOKEN or not SLACK_CHANNEL_ID:
            print("⚠️ SLACK_BOT_TOKEN or SLACK_CHANNEL_ID not set. Please check your .env file.")
            return

        print(f"[{datetime.now().isoformat()}] Polling Slack for new messages...")
        url = "https://slack.com/api/conversations.history"
        headers = {"Authorization": f"Bearer {SLACK_BOT_TOKEN}"}
        params = {
            "channel": SLACK_CHANNEL_ID,
            "oldest": self.last_ts
        }

        try:
            response = requests.get(url, headers=headers, params=params)
            data = response.json()

            if not data.get("ok"):
                print(f"❌ Slack API Error: {data.get('error')}")
                return

            messages = data.get("messages", [])
            if not messages:
                print("No new messages.")
                return

            # Process messages in chronological order
            for msg in reversed(messages):
                ts = msg.get("ts")
                if ts <= self.last_ts:
                    continue
                
                self.process_message(msg)
                self.last_ts = ts
                self._save_state(ts)

        except Exception as e:
            print(f"❌ Error polling Slack: {e}")

    def process_message(self, msg):
        user = msg.get("user")
        text = msg.get("text")
        files = msg.get("files", [])

        print(f"📩 New message from {user}: {text}")

        # Handle voice clips / audio files
        for file in files:
            if file.get("mimetype", "").startswith("audio/"):
                self.download_voice_clip(file)

        # Trigger Genesis Brain (Integration point)
        # Note: In a real scenario, this would call a Genesis service or CLI
        self.trigger_genesis_response(text, user)

    def download_voice_clip(self, file_info):
        file_url = file_info.get("url_private_download")
        file_name = f"voice_{file_info.get('id')}_{file_info.get('timestamp')}.mp4" # Slack voice clips are often m4a/mp4
        save_path = VOICE_DIR / file_name

        print(f"🎙️ Downloading voice clip: {file_name}")
        headers = {"Authorization": f"Bearer {SLACK_BOT_TOKEN}"}
        
        try:
            r = requests.get(file_url, headers=headers)
            with open(save_path, "wb") as f:
                f.write(r.content)
            print(f"✅ Voice clip saved to {save_path}")
            
            # TODO: Integrate with Gemini for transcription and processing
            
        except Exception as e:
            print(f"❌ Failed to download voice clip: {e}")

    def trigger_genesis_response(self, text, user_id):
        # Placeholder for Genesis interaction
        # This could be a call to `core/genesis_coordinator.py` or similar
        print(f"🤖 Genesis is thinking about: {text}")
        
        # Post a placeholder response back to Slack
        self.send_slack_message(f"Genesis received your message: '{text}'. Processing...")

    def send_slack_message(self, text):
        url = "https://slack.com/api/chat.postMessage"
        headers = {"Authorization": f"Bearer {SLACK_BOT_TOKEN}"}
        payload = {
            "channel": SLACK_CHANNEL_ID,
            "text": text
        }
        requests.post(url, headers=headers, json=payload)

if __name__ == "__main__":
    bridge = SlackNomadBridge()
    while True:
        bridge.poll_messages()
        time.sleep(300) # Poll every 5 minutes
