import sys
import subprocess
import argparse

html_file_path = './email.html'

def send_html_email(recipient):
    try:
        with open(html_file_path, 'r', encoding='utf-8') as file:
            html_content = file.read()
        
        process = subprocess.Popen(
            ['/usr/sbin/sendmail', f'{recipient}'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        email_headers = f'From: Pup Tech <pups@fuzzybench.com>\nTo: {recipient}\nSubject: Generated text can\'t stop pups from naps\nContent-Type: text/html; charset=utf-8\n\n'
        
        _, stderr = process.communicate(input=email_headers + html_content)
        
        if process.returncode != 0:
            raise Exception(f"sendmail failed with error: {stderr}")
        
        print(f'{email_headers + html_content}')
    except FileNotFoundError:
        raise Exception("HTML file not found")
    except Exception as e:
        raise Exception(f"Error sending email: {str(e)}")

def main():
    parser = argparse.ArgumentParser(description='Send HTML file as email body using sendmail')
    parser.add_argument('recipient', help='Recipient email address')
    
    args = parser.parse_args()
    
    try:
        send_html_email( args.recipient)
        print("Email sent successfully")
    except Exception as e:
        print(f"Failed to send email: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()