import os
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("diagnose-email")

def diagnose():
    print("🔍 Starting Email Capability Diagnosis...")
    client = SuperOfficeClient()
    if not client.access_token:
        print("❌ Auth failed.")
        return

    # 1. Check Licenses / Capabilities via Associate/Me
    print("\n--- 1. User & License Check ---")
    try:
        me = client._get("Associate/Me")
        if me:
            print(f"User: {me.get('Name')} (ID: {me.get('AssociateId')})")
            print(f"Type: {me.get('Type')}")
            # Check for specific functional rights if available in the object
            # (Note: API often hides raw license keys, but let's check what we get)
            print("Function Rights (TableRight):", me.get("TableRight"))
        else:
            print("❌ Could not fetch current user.")
    except Exception as e:
        print(f"❌ User check failed: {e}")

    # 2. Check User Preferences (Email Settings)
    # Endpoint: GET /Preference/{section}/{key}
    # We look for 'Mail' section preferences
    print("\n--- 2. Email Preferences (System & User) ---")
    pref_keys = [
        ("Mail", "EmailClient"),
        ("Mail", "EmailSystem"),
        ("System", "SoProtocol"),
        ("Visual", "UseWebTools")
    ]
    
    for section, key in pref_keys:
        try:
            # Note: The API for preferences might be /Preference/<Section>/<Key>
            # or require a search. Let's try direct access first.
            res = client._get(f"Preference/{section}/{key}")
            if res:
                print(f"✅ Preference '{section}/{key}': {json.dumps(res, indent=2)}")
            else:
                print(f"❓ Preference '{section}/{key}' not found or empty.")
        except Exception as e:
            print(f"⚠️ Error checking preference '{section}/{key}': {e}")

    # 3. Check for specific functional rights (Archive/List)
    # If we can access 'ShipmentType' list, we might have Marketing
    print("\n--- 3. Marketing Capability Check ---")
    try:
        shipment_types = client._get("List/ShipmentType/Items")
        if shipment_types:
            print(f"✅ Found {len(shipment_types)} Shipment Types (Marketing module likely active).")
            for st in shipment_types:
                print(f"   - {st.get('Name')} (ID: {st.get('Id')})")
        else:
            print("❌ No Shipment Types found (Marketing module might be inactive/restricted).")
    except Exception as e:
        print(f"❌ Error checking Shipment Types: {e}")

    # 4. Check Document Template for 'Email'
    print("\n--- 4. Document Template Configuration ---")
    try:
        # We know ID 157 exists, let's inspect it closely
        tmpl = client._get("DocumentTemplate/157")
        if tmpl:
            print(f"Template 157: {tmpl.get('Name')}")
            print(f"  - Generator: {tmpl.get('Generator')}") # Important! 
            print(f"  - Filename: {tmpl.get('Filename')}")
            print(f"  - Direction: {tmpl.get('Direction')}")
        else:
            print("❌ Template 157 not found via ID.")
    except Exception as e:
        print(f"❌ Error checking Template 157: {e}")

if __name__ == "__main__":
    diagnose()
