import os
import requests
import json
import logging
from dotenv import load_dotenv
load_dotenv(override=True)
from superoffice_client import SuperOfficeClient
from config import settings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("mailing-test")

def create_mailing(person_id: int):
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # 1. Get Person & Marketing Texts
    person = client._get(f"Person/{person_id}")
    if not person:
        print(f"❌ Person {person_id} not found.")
        return
    
    email_address = person.get("Emails", [{}])[0].get("Value")
    if not email_address:
        print(f"❌ Person {person_id} has no email address.")
        return
    
    udefs = person.get("UserDefinedFields", {})
    subject = udefs.get(settings.UDF_SUBJECT)
    intro = udefs.get(settings.UDF_INTRO)
    proof = udefs.get(settings.UDF_SOCIAL_PROOF)
    
    if not all([subject, intro, proof]):
        print("❌ Marketing texts missing in Person UDFs. Run provisioning first.")
        return

    full_body = f"{intro}\n\n{proof}\n\nAbmelden: {udefs.get(settings.UDF_UNSUBSCRIBE_LINK)}"

    # 2. Create a "Shipment" (Individual Mailing)
    # Based on SO Documentation for Marketing API
    # We try to create a Shipment directly.
    
    payload = {
        "Name": f"Gemini Outreach: {subject}",
        "Subject": subject,
        "Body": full_body,
        "DocumentTemplateId": 157, # Ausg. E-Mail
        "ShipmentType": "Email",
        "AssociateId": 528, # RCGO
        "ContactId": person.get("Contact", {}).get("ContactId"),
        "PersonId": person_id,
        "Status": "Ready" # This might trigger the internal SO send process
    }

    print(f"📤 Creating Shipment for {email_address}...")
    try:
        # Endpoints to try: /Shipment or /Mailing
        # Let's try /Shipment
        resp = client._post("Shipment", payload)
        if resp:
            print(f"✅ Shipment created successfully! ID: {resp.get('ShipmentId')}")
            print(json.dumps(resp, indent=2))
        else:
            print("❌ Shipment creation returned no data.")
    except Exception as e:
        print(f"❌ Shipment API failed: {e}")

if __name__ == "__main__":
    create_mailing(193036)
