import sys
import os
import json
import requests
from datetime import datetime, timedelta
from dotenv import load_dotenv

# Ensure we use the correct config and client from the connector-superoffice subdir
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'connector-superoffice')))

from superoffice_client import SuperOfficeClient

def run_final_test():
    print("🚀 Starting Final Mailing Test for floke.com@gmail.com...")
    
    # 1. Initialize Client
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # 2. Use Target Contact (Bremer Abenteuerland)
    contact_id = 171185
    print(f"✅ Using Contact ID: {contact_id}")

    # 3. Use Created Person
    person_id = 193092
    print(f"✅ Using Person ID: {person_id} (floke.com@gmail.com)")

    # 4. Attempt Shipment (Mailing)
    print("📤 Attempting to create Shipment (the direct email send)...")
    shipment_payload = {
        "Name": "Gemini Diagnostics: Test Shipment",
        "Subject": "Hallo aus der Gemini GTM Engine",
        "Body": "Dies ist ein Testversuch für den direkten E-Mail-Versand via SuperOffice API.",
        "DocumentTemplateId": 157, # Outgoing Email (ID 157 is confirmed from previous runs as typical)
        "ShipmentType": "Email",
        "AssociateId": 528, # API User RCGO
        "ContactId": contact_id,
        "PersonId": person_id,
        "Status": "Ready"
    }

    try:
        shipment_resp = client._post("Shipment", shipment_payload)
        if shipment_resp:
            print("✅ UNEXPECTED SUCCESS: Shipment created!")
            print(json.dumps(shipment_resp, indent=2))
        else:
            print("❌ Shipment creation returned empty response.")
    except Exception as e:
        print(f"❌ EXPECTED FAILURE: Shipment creation failed as predicted.")
        print(f"Error details: {e}")

    # 5. Fallback: Create Appointment as "Proof of Work"
    print("\n📅 Running Workaround: Creating Appointment instead...")
    appt_resp = client.create_appointment(
        subject="KI: E-Mail Testversuch an floke.com@gmail.com",
        description="Hier würde der E-Mail-Text stehen, der aufgrund technischer Blockaden (Mailing-Modul/Identität) nicht direkt versendet werden konnte.",
        contact_id=contact_id,
        person_id=person_id
    )
    
    if appt_resp:
        appt_id = appt_resp.get("appointmentId") or appt_resp.get("AppointmentId")
        print(f"✅ Workaround Successful: Appointment ID: {appt_id}")
        print(f"🔗 Link: https://online3.superoffice.com/Cust26720/default.aspx?appointment_id={appt_id}")
    else:
        print("❌ Workaround (Appointment) failed too.")

if __name__ == "__main__":
    run_final_test()
