import logging
from datetime import datetime
from pathlib import Path
import json

class EmailLogger:
    def __init__(self, log_file="email_auth_log.txt"):
        self.log_file = log_file
        self.setup_logging()

    def setup_logging(self):
        # Create directory if it doesn't exist
        Path(self.log_file).parent.mkdir(parents=True, exist_ok=True)
        
        # Setup logging configuration
        logging.basicConfig(
            filename=self.log_file,
            level=logging.INFO,
            format='%(asctime)s\t%(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )

    def log_auth_email(self, email: str, auth_code: str, sent_successfully: bool = True):
        """Log when an authentication email is sent"""
        try:
            entry = {
                "email": email,
                "auth_code": auth_code,
                "timestamp": datetime.now().isoformat(),
                "status": "sent" if sent_successfully else "failed",
                "verified": False
            }
            
            logging.info(json.dumps(entry))
            
        except Exception as e:
            logging.error(f"Error logging email: {str(e)}")

    def mark_as_verified(self, email: str, auth_code: str):
        """Mark an email as verified when authentication is successful"""
        try:
            # Read the existing log file
            with open(self.log_file, 'r') as f:
                lines = f.readlines()
            
            # Update the verification status in memory
            updated_lines = []
            for line in lines:
                try:
                    timestamp, json_str = line.strip().split('\t')
                    entry = json.loads(json_str)
                    
                    if (entry['email'] == email and 
                        entry['auth_code'] == auth_code and 
                        not entry['verified']):
                        entry['verified'] = True
                        entry['verification_time'] = datetime.now().isoformat()
                    
                    updated_lines.append(f"{timestamp}\t{json.dumps(entry)}\n")
                except:
                    updated_lines.append(line)
            
            # Write back to the file
            with open(self.log_file, 'w') as f:
                f.writelines(updated_lines)
                
        except Exception as e:
            logging.error(f"Error marking email as verified: {str(e)}")

    def get_verification_status(self, email: str) -> list:
        """Get verification history for an email"""
        try:
            history = []
            with open(self.log_file, 'r') as f:
                for line in f:
                    try:
                        timestamp, json_str = line.strip().split('\t')
                        entry = json.loads(json_str)
                        if entry['email'] == email:
                            history.append(entry)
                    except:
                        continue
            return history
        except Exception as e:
            logging.error(f"Error getting verification status: {str(e)}")
            return []
