import os
import json
import requests
from dotenv import load_dotenv

# Load environment variables
load_dotenv(override=True)

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
NOTION_API_KEY = os.getenv("NOTION_API_KEY")

# Configuration
NOTION_DB_INDUSTRIES = "2ec88f4285448014ab38ea664b4c2b81"  # ID aus deinen Links

def get_vertical_data(vertical_name):
    """Fetches Pains/Gains for a specific Vertical from Notion."""
    url = f"https://api.notion.com/v1/databases/{NOTION_DB_INDUSTRIES}/query"
    headers = {
        "Authorization": f"Bearer {NOTION_API_KEY}",
        "Notion-Version": "2022-06-28",
        "Content-Type": "application/json"
    }
    payload = {
        "filter": {
            "property": "Vertical",
            "title": {
                "contains": vertical_name
            }
        }
    }
    
    response = requests.post(url, headers=headers, json=payload)
    if response.status_code == 200:
        results = response.json().get("results", [])
        if results:
            page = results[0]
            props = page['properties']
            
            # Extract Text from Rich Text fields
            pains = props.get('Pains', {}).get('rich_text', [])
            gains = props.get('Gains', {}).get('rich_text', [])
            
            pain_text = pains[0]['plain_text'] if pains else "N/A"
            gain_text = gains[0]['plain_text'] if gains else "N/A"
            
            return {
                "vertical": vertical_name,
                "pains": pain_text,
                "gains": gain_text
            }
    return None

def generate_copy_with_gemini(vertical_data, persona_role, persona_pains):
    """
    Generates the 3 text blocks using Gemini.
    """
    url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={GEMINI_API_KEY}"
    
    # Der Prompt (Dein Template)
    prompt_text = f"""
    Du bist ein kompetenter Lösungsberater und brillanter Texter.
    AUFGABE: Erstelle 3 Textblöcke (Subject, Introduction_Textonly, Industry_References_Textonly) für eine E-Mail.
    
    --- KONTEXT ---
    ZIELBRANCHE: {vertical_data['vertical']}
    BRANCHEN-HERAUSFORDERUNGEN (PAIN POINTS): {vertical_data['pains']}
    LÖSUNGS-VORTEILE (GAINS): {vertical_data['gains']}
    
    ANSPRECHPARTNER: {persona_role}
    PERSÖNLICHE HERAUSFORDERUNGEN DES ANSPRECHPARTNERS: {persona_pains}
    
    REFERENZKUNDEN: "Wir arbeiten bereits mit Marktführern in Ihrer Branche." (Platzhalter)
    
    --- DEINE AUFGABE ---
    1. Subject: Formuliere eine kurze Betreffzeile (max. 5 Wörter). Richte sie direkt an einem Pain Point aus.
    2. Introduction_Textonly: Formuliere einen Einleitungstext (2 Sätze).
       - Fokus: Brücke zwischen Problem und Lösung.
    3. Industry_References_Textonly: Formuliere einen Social Proof Satz.
    
    --- FORMAT ---
    Antworte NUR mit reinem JSON:
    {{
      "Subject": "...",
      "Introduction_Textonly": "...",
      "Industry_References_Textonly": "..."
    }}
    """
    
    payload = {
        "contents": [{"parts": [{"text": prompt_text}]}],
        "generationConfig": {"responseMimeType": "application/json"}
    }
    
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            return json.loads(response.json()['candidates'][0]['content']['parts'][0]['text'])
        else:
            print(f"Gemini Error: {response.text}")
            return None
    except Exception as e:
        print(f"Error: {e}")
        return None

if __name__ == "__main__":
    # TEST RUN
    
    # 1. Daten holen (Beispiel: Logistics)
    print("Fetching Vertical Data...")
    vertical = get_vertical_data("Logistics - Warehouse")
    
    if vertical:
        print(f"Loaded: {vertical['vertical']}")
        
        # 2. Persona definieren (Beispiel: Operativer Entscheider)
        role = "Logistikleiter / Operations Manager"
        role_pains = "Stillstand, Personalmangel, Stress, Unfallgefahr"
        
        # 3. Generieren
        print("Generating Copy...")
        copy = generate_copy_with_gemini(vertical, role, role_pains)
        
        print("\n--- RESULT ---")
        print(json.dumps(copy, indent=2, ensure_ascii=False))
    else:
        print("Vertical not found.")
