#!/usr/bin/env python3
"""
Email Tracking Utilities
Prevents duplicates, tracks sequences
"""
import csv
import sys
from datetime import datetime

TRACKING_FILE = 'email_tracking.csv'

def get_sent_emails():
    """Returns set of all emails already sent"""
    sent = set()
    try:
        with open(TRACKING_FILE, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            next(reader)  # Skip header
            for row in reader:
                if len(row) > 1 and row[1]:
                    sent.add(row[1].strip().lower())
    except FileNotFoundError:
        pass
    return sent

def check_duplicate(email):
    """Check if email was already sent"""
    sent_emails = get_sent_emails()
    return email.strip().lower() in sent_emails

def log_sent(school_name, email, status='SENT', notes=''):
    """Log a new sent email"""
    now = datetime.now()
    with open(TRACKING_FILE, 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow([
            school_name, email,
            now.strftime('%Y-%m-%d'), now.strftime('%H:%M:%S'),
            status, '', '',  # No reply yet
            '', '', '',  # No follow-ups
            notes
        ])

def update_reply(email, reply_content, status='REPLIED'):
    """Update status when they reply"""
    rows = []
    with open(TRACKING_FILE, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        rows = list(reader)
    
    now = datetime.now().strftime('%Y-%m-%d')
    
    with open(TRACKING_FILE, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        for row in rows:
            if len(row) > 1 and row[1].strip().lower() == email.strip().lower():
                row[5] = now  # Reply date
                row[6] = reply_content[:100]  # Reply content (truncated)
                row[7] = status  # Status
            writer.writerow(row)

def get_status(email):
    """Get current status of an email"""
    sent_emails = get_sent_emails()
    if email.strip().lower() not in sent_emails:
        return 'NOT_SENT'
    
    with open(TRACKING_FILE, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        for row in reader:
            if len(row) > 4 and row[1].strip().lower() == email.strip().lower():
                return row[4]
    return 'UNKNOWN'

# CLI Interface
if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage:")
        print("  python3 email_tracker.py check <email>")
        print("  python3 email_tracker.py log '<school>' <email>")
        print("  python3 email_tracker.py status <email>")
        sys.exit(1)
    
    command = sys.argv[1]
    
    if command == 'check':
        email = sys.argv[2] if len(sys.argv) > 2 else ''
        if check_duplicate(email):
            print(f"DUPLICATE: {email} was already sent!")
            sys.exit(1)
        else:
            print(f"OK: {email} - not sent yet")
            
    elif command == 'log':
        if len(sys.argv) < 4:
            print("Usage: python3 email_tracker.py log '<school>' <email>")
            sys.exit(1)
        school = sys.argv[2]
        email = sys.argv[3]
        log_sent(school, email)
        print(f"LOGGED: {school} -> {email}")
        
    elif command == 'status':
        email = sys.argv[2] if len(sys.argv) > 2 else ''
        status = get_status(email)
        print(f"Status: {status}")