import requests
import json
import os
from datetime import datetime

# Default-Webhook (Platzhalter) - sollte in .env stehen
DEFAULT_WEBHOOK_URL = os.getenv("TEAMS_WEBHOOK_URL", "")

def send_approval_card(job_uuid, customer_name, time_string, webhook_url=DEFAULT_WEBHOOK_URL, api_base_url="http://localhost:8004"):
    """
    Sendet eine Adaptive Card an Teams mit Approve/Deny Buttons.
    """
    
    # Die URL unserer API (muss von außen erreichbar sein, z.B. via ngrok oder Server-IP)

    
    card_payload = {
        "type": "message",
        "attachments": [
            {
                "contentType": "application/vnd.microsoft.card.adaptive",
                "contentUrl": None,
                "content": {
                    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
                    "type": "AdaptiveCard",
                    "version": "1.4",
                    "body": [
                        {
                            "type": "TextBlock",
                            "text": f"🤖 Automatisierte E-Mail an {customer_name} (via Trading Twins) wird um {time_string} Uhr ausgesendet.",
                            "weight": "Bolder",
                            "size": "Medium"
                        },
                        {
                            "type": "TextBlock",
                            "text": f"Wenn Du bis {time_string} Uhr NICHT reagierst, wird die generierte E-Mail automatisch ausgesendet.",
                            "isSubtle": True,
                            "wrap": True
                        }
                    ],
                    "actions": [
                        {
                            "type": "Action.OpenUrl",
                            "title": "✅ JETZT Aussenden",
                            "url": f"{api_base_url}/send_now/{job_uuid}"
                        },
                        {
                            "type": "Action.OpenUrl",
                            "title": "❌ STOP Aussendung",
                            "url": f"{api_base_url}/stop/{job_uuid}"
                        }
                    ]
                }
            }
        ]
    }
    
    try:
        response = requests.post(webhook_url, json=card_payload)
        response.raise_for_status()
        return True
    except Exception as e:
        logging.error(f"Fehler beim Senden an Teams: {e}")
        return False
