#!/usr/bin/env python3
"""
邮件服务命令行工具
"""

import argparse
import sys
from mail_service.mail_service import EmailService


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='邮件服务命令行工具')
    parser.add_argument('--email', help='邮箱地址')
    parser.add_argument('--password', help='邮箱密码')
    parser.add_argument('--provider', help='邮箱提供商')
    
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # 列出邮件命令
    list_parser = subparsers.add_parser('list', help='列出邮件')
    list_parser.add_argument('--folder', default='INBOX', help='邮件文件夹')
    list_parser.add_argument('--limit', type=int, default=10, help='显示邮件数量')
    
    # 搜索邮件命令
    search_parser = subparsers.add_parser('search', help='搜索邮件')
    search_parser.add_argument('--query', help='搜索关键词')
    search_parser.add_argument('--from', dest='from_addr', help='发件人地址')
    search_parser.add_argument('--to', dest='to_addr', help='收件人地址')
    search_parser.add_argument('--subject', help='主题关键词')
    search_parser.add_argument('--folder', default='INBOX', help='邮件文件夹')
    search_parser.add_argument('--limit', type=int, default=10, help='显示邮件数量')
    
    # 发送邮件命令
    send_parser = subparsers.add_parser('send', help='发送邮件')
    send_parser.add_argument('--to', required=True, help='收件人地址')
    send_parser.add_argument('--subject', required=True, help='邮件主题')
    send_parser.add_argument('--body', required=True, help='邮件正文')
    send_parser.add_argument('--html', help='HTML 格式正文')
    send_parser.add_argument('--cc', help='抄送地址（逗号分隔）')
    send_parser.add_argument('--bcc', help='密送地址（逗号分隔）')
    send_parser.add_argument('--attachment', help='附件文件路径（逗号分隔）')
    
    # 删除邮件命令
    delete_parser = subparsers.add_parser('delete', help='删除邮件')
    delete_parser.add_argument('--uid', required=True, help='邮件 UID')
    delete_parser.add_argument('--folder', default='INBOX', help='邮件文件夹')
    
    # 获取邮件详情命令
    get_parser = subparsers.add_parser('get', help='获取邮件详情')
    get_parser.add_argument('--uid', required=True, help='邮件 UID')
    get_parser.add_argument('--folder', default='INBOX', help='邮件文件夹')
    
    # 获取邮件数量命令
    count_parser = subparsers.add_parser('count', help='获取邮件数量')
    count_parser.add_argument('--folder', default='INBOX', help='邮件文件夹')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    try:
        # 创建邮件服务实例
        email_service = EmailService(
            email_address=args.email,
            password=args.password,
            provider=args.provider,
        )
        
        if args.command == 'list':
            emails = email_service.list_emails(args.folder, args.limit)
            print(f"\n{args.folder} 中的最近 {len(emails)} 封邮件:")
            for i, email_info in enumerate(emails, 1):
                print(f"{i}. 主题: {email_info['subject']}")
                print(f"   发件人: {email_info['from']}")
                print(f"   日期: {email_info['date']}")
                print(f"   UID: {email_info['uid']}")
                print()
        
        elif args.command == 'search':
            search_results = email_service.search_emails(
                query=args.query,
                from_addr=args.from_addr,
                to_addr=args.to_addr,
                subject=args.subject,
                folder=args.folder,
                limit=args.limit
            )
            print(f"\n搜索到 {len(search_results)} 封邮件:")
            for i, email_info in enumerate(search_results, 1):
                print(f"{i}. 主题: {email_info['subject']}")
                print(f"   发件人: {email_info['from']}")
                print(f"   日期: {email_info['date']}")
                print(f"   UID: {email_info['uid']}")
                print()
        
        elif args.command == 'send':
            cc_list = args.cc.split(',') if args.cc else None
            bcc_list = args.bcc.split(',') if args.bcc else None
            attachment_list = args.attachment.split(',') if args.attachment else None
            
            success = email_service.send_email(
                to_address=args.to,
                subject=args.subject,
                body=args.body,
                html_body=args.html,
                cc=cc_list,
                bcc=bcc_list,
                attachments=attachment_list
            )
            
            if success:
                print("邮件发送成功！")
            else:
                print("邮件发送失败！")
                sys.exit(1)
        
        elif args.command == 'delete':
            success = email_service.delete_email(args.uid, args.folder)
            if success:
                print(f"邮件 {args.uid} 删除成功！")
            else:
                print(f"邮件 {args.uid} 删除失败！")
                sys.exit(1)
        
        elif args.command == 'get':
            email_detail = email_service.get_email_by_uid(args.uid, args.folder)
            if email_detail:
                print(f"\n邮件详情 (UID: {args.uid}):")
                print(f"主题: {email_detail['subject']}")
                print(f"发件人: {email_detail['from']}")
                print(f"收件人: {email_detail['to']}")
                print(f"日期: {email_detail['date']}")
                print(f"内容类型: {email_detail['content_type']}")
                print(f"内容:\n{email_detail['body']}")
            else:
                print(f"未找到邮件 {args.uid}")
                sys.exit(1)
        
        elif args.command == 'count':
            count = email_service.get_email_count(args.folder)
            print(f"{args.folder} 中有 {count} 封邮件")
    
    except Exception as e:
        print(f"错误: {str(e)}")
        sys.exit(1)


if __name__ == "__main__":
    main()
