import json
import subprocess
import os
from datetime import datetime, timedelta
import re

# --- Configuration ---
GOG_ACCOUNT = "ahmad@bigalc.com" # User's primary email for gog CLI
OUTPUT_DIR = "crm_data" # Directory to store extracted CRM data

# Ensure output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)

# --- Helper Functions ---
def run_gog_command(command_parts):
    full_command = ["gog"]
    full_command.extend(command_parts)
    
    print(f"Running command: {' '.join(full_command)}")
    try:
        result = subprocess.run(full_command, capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Error running gog command: {' '.join(full_command)}")
        print(f"Stderr: {e.stderr}")
        raise e

def summarize_text(text, max_length=200):
    if not text:
        return ""
    if len(text) <= max_length:
        return text
    return text[:max_length] + "..."

# --- Ingestion Functions ---
def ingest_emails():
    print(f"Ingesting emails for {GOG_ACCOUNT}...")
    try:
        email_output = run_gog_command(
            ["gmail", "search", "--account", GOG_ACCOUNT, "label:inbox", "--json"]
        )
        emails = json.loads(email_output)
        
        ingested_count = 0
        if emails and 'threads' in emails: # Corrected from 'messages' to 'threads'
            for thread in emails['threads']: # Iterate over threads
                message_id = thread.get('id')
                sender = thread.get('from', '')
                subject = thread.get('subject', '')
                date_val = thread.get('date', '') # Date is directly available in thread summary
                # snippet = "" # Snippet is not directly available in thread summary, requires getting message.

                print(f"\n--- Email ---")
                print(f"  ID: {message_id}")
                print(f"  From: {sender}")
                print(f"  Subject: {subject}")
                print(f"  Date: {date_val}")
                # For a full CRM, we'd eventually store/process the snippet/body
                ingested_count += 1
        print(f"Ingested {ingested_count} emails.")
    except Exception as e:
        print(f"Error ingesting emails: {e}")

def ingest_calendar_events():
    print(f"\nIngesting calendar events for {GOG_ACCOUNT}...")
    try:
        calendar_output = run_gog_command(
            ["calendar", "list"]
        )
        # Parse text output for calendar events using re.split(r'\s{2,}')
        lines = calendar_output.strip().split('\n')
        if len(lines) > 1: # Skip header line
            events_data = []
            # Headers: ID START END SUMMARY
            for line in lines[1:]:
                if not line.strip():
                    continue
                parts = re.split(r'\s{2,}', line.strip(), maxsplit=3) # Split into ID, START, END, SUMMARY
                if len(parts) >= 4:
                    event_id = parts[0].strip()
                    start_time = parts[1].strip()
                    end_time = parts[2].strip()
                    summary = parts[3].strip()
                    events_data.append({
                        "ID": event_id,
                        "START": start_time,
                        "END": end_time,
                        "SUMMARY": summary
                    })
                else:
                    print(f"Warning: Could not parse calendar line (split by 2+ spaces failed): '{line.strip()}'")
            
            ingested_count = 0
            for event in events_data:
                print(f"\n--- Calendar Event ---")
                print(f"  ID: {event.get('ID')}")
                print(f"  Summary: {event.get('SUMMARY')}")
                print(f"  Time: {event.get('START')} to {event.get('END')}")
                ingested_count += 1
            print(f"Ingested {ingested_count} calendar events.")
        else:
            print("No calendar events found.")
    except Exception as e:
        print(f"Error ingesting calendar events: {e}")

# (ingest_google_tasks function remains commented out as it's skipped by user)

# --- Main execution ---
if __name__ == "__main__":
    ingest_emails()
    ingest_calendar_events()
    # ingest_google_tasks() # Skipped by user's request
