import logging
import random

from nyahome.config import config_manager
from nyahome.core.core_abc.otp import OtpMemoryStore
from nyahome.core.send_email import SendEmailItem, email_sender_queue
from nyahome.core.template_render import template_render

logger = logging.getLogger(__name__)


def generate_random_code() -> str:
    return f"{random.randint(0, 999999):06d}"


class EmailOtpMemoryStore(OtpMemoryStore):
    def __init__(self) -> None:
        super().__init__("EmailOtpMemoryStore")

    async def generate_and_send(self, user_id: int, address: str, email_reason: str) -> bool:
        if not self._check(user_id, address):
            logger.error(f"该邮件地址 {address} 或用户 {user_id} 已有待处理的邮件验证码。")
            return False
        code = generate_random_code()
        site_name = config_manager.get("site_name", "Nya Home")
        html = template_render.render_2fa_otp(
            site_name=site_name,
            site_url=config_manager.get("site_url"),
            email_reason=email_reason,
            otp_number=code,
        )
        await email_sender_queue.put(
            SendEmailItem(
                to=address,
                subject=f"{site_name} - 一次性邮件验证码",
                body=html,
            )
        )
        self._put(user_id, address, code)
        logger.info(f"已经向邮件地址 {address} 发送用户 {user_id} 的一次性邮件验证码 {code}")
        return True


email_otp_memory_store = EmailOtpMemoryStore()
