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

# Setup Logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("create-email-test")

def create_email_document(person_id_input: int):
    print(f"🚀 Creating Email Document for Person ID {person_id_input}...")

    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed. Check .env")
        return

    # --- TARGET PERSON ---
    target_person_id = person_id_input
    contact_id = None
    person_id = None
    
    print(f"📡 Fetching target Person {target_person_id}...")
    try:
        person = client._get(f"Person/{target_person_id}")
        if not person:
            print(f"❌ Person {target_person_id} not found.")
            return
            
        print(f"✅ Found Person: {person.get('Firstname')} {person.get('Lastname')}")
        
        # Get associated Contact ID
        contact_id = person.get('Contact', {}).get('ContactId')
        if not contact_id:
             print("❌ Person has no associated company (ContactId).")
             return
             
        # Verify Contact
        contact = client._get(f"Contact/{contact_id}")
        if contact:
            print(f"✅ Associated Company: {contact.get('Name')} (ID: {contact_id})")
        
        person_id = target_person_id

    except Exception as e:
        print(f"❌ Error fetching Person/Contact: {e}")
        return

    if not contact_id or not person_id:
        print("❌ Could not resolve Contact/Person IDs.")
        return

    # 2. Define Email Content
    # Get Email Address from Person
    email_address = person.get("Emails", [{}])[0].get("Value", "k.A.")
    
    subject = f"Optimierung Ihrer Service-Prozesse (Referenz: {person.get('Firstname')} {person.get('Lastname')})"
    
    # We use the UDFs we already found in Person 193036
    udefs = person.get("UserDefinedFields", {})
    intro = udefs.get(settings.UDF_INTRO, "Guten Tag,")
    proof = udefs.get(settings.UDF_SOCIAL_PROOF, "Wir unterstützen Unternehmen bei der Automatisierung.")
    unsub = udefs.get(settings.UDF_UNSUBSCRIBE_LINK, "")
    
    body = f"""{intro}

{proof}

Abmelden: {unsub}

Viele Grüße,
Christian Godelmann
RoboPlanet"""

    # 3. Create Document Payload
    template_id = 157 

    payload = {
        "Name": f"Outreach: {email_address}", # Internal Name with Email for visibility
        "Header": subject,                    # Subject Line
        "Contact": {"ContactId": contact_id},
        "Person": {"PersonId": person_id},
        "DocumentTemplate": {"DocumentTemplateId": template_id},
        "Content": body
    }

    print(f"📤 Creating E-Mail draft for {email_address}...")
    try:
        doc = client._post("Document", payload)
        if doc:
            doc_id = doc.get('DocumentId')
            print(f"✅ Document Created Successfully!")
            print(f"   ID: {doc_id}")
            print(f"   Recipient: {email_address}")
            print(f"   Template: {doc.get('DocumentTemplate', {}).get('Name')}")
            
            # 3b. Upload Content (Critical Step to avoid 'Checkout Error')
            print(f"📤 Uploading content stream to Document {doc_id}...")
            try:
                content_bytes = body.encode('utf-8')
                
                # Manual request because _request_with_retry assumes JSON
                headers = client.headers.copy()
                headers["Content-Type"] = "application/octet-stream" 
                
                res = requests.put(
                    f"{client.base_url}/Document/{doc_id}/Content",
                    data=content_bytes,
                    headers=headers
                )
                if res.status_code in [200, 204]:
                    print("✅ Content uploaded successfully.")
                else:
                    print(f"⚠️ Content upload failed: {res.status_code} {res.text}")
                    
            except Exception as e:
                print(f"⚠️ Content upload error: {e}")

            # Construct direct link
            env = settings.SO_ENVIRONMENT
            cust_id = settings.SO_CONTEXT_IDENTIFIER
            
            doc_link = f"https://{env}.superoffice.com/{cust_id}/default.aspx?document_id={doc_id}"

            # 4. Create Linked Appointment (Activity)
            print("📅 Creating Linked Appointment (Email Sent Activity)...")
            appt_payload = {
                "Description": body,
                "Contact": {"ContactId": contact_id},
                "Person": {"PersonId": person_id},
                "Task": {"Id": 6}, # 6 = Document / Email Out
                "Document": {"DocumentId": doc_id},
                "MainHeader": f"E-Mail: {subject}"[:40] 
            }
            try:
                appt = client._post("Appointment", appt_payload)
                if appt:
                     appt_id = appt.get('AppointmentId')
                     print(f"✅ Appointment Created: {appt_id}")
                     
                     appt_link = f"https://{env}.superoffice.com/{cust_id}/default.aspx?appointment_id={appt_id}"
                     
                     print(f"\n--- WICHTIG: NUTZEN SIE DIESEN LINK ---")
                     print(f"Da das Dokument selbst ('Cannot check out') oft blockiert,")
                     print(f"öffnen Sie bitte die AKTIVITÄT. Dort steht der Text im Beschreibungsfeld:")
                     print(f"🔗 {appt_link}")
                     print(f"---------------------------------------\n")
                     
                     print(f"(Backup Link zum Dokument: {doc_link})")

                else:
                     print("⚠️ Failed to create appointment (None response).")
            except Exception as e:
                print(f"⚠️ Failed to create appointment: {e}")

        else:
            print("❌ Failed to create document (Response was empty/None).")

    except Exception as e:
        print(f"❌ Error creating document: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Create a test email document in SuperOffice.')
    parser.add_argument('person_id', type=int, help='The SuperOffice Person ID to attach the email to.')
    
    args = parser.parse_args()
    
    create_email_document(args.person_id)