import requests
import random
import time , os
import hmac
import hashlib
from flask import session, current_app
from flask_mail import Message
from extensions import mail
from flask_babel import Babel, _ 
import resend


IPPANEL_URL = "http://ippanel.com/api/select"
IPPANEL_USER = "9168822353"
IPPANEL_PASS = "Modir@2353"
FROM_NUMBER = "3000505"
PATTERN_CODE = "ndpra5cy82p2xcf"

SECRET = "TeqSr26&Fk1c!f*5^2fj&^fDg"



def otp_code_generate():
    # Generate 6-digit OTP
    code = str(random.randint(100000, 999999))
    return code


def _hmac_otp(otp: str):
    return hmac.new(SECRET.encode(), otp.encode(), hashlib.sha256).hexdigest()

def generate_and_store_otp(ttl_seconds: int = 300):
    otp = otp_code_generate()
    session['otp_hmac'] = _hmac_otp(otp)
    session['otp_expires_at'] = int(time.time()) + ttl_seconds
    session['otp_attempts'] = 0
    return otp

def check_otp_is_valid(recsive_otp):
    return hmac.compare_digest(session['otp_hmac'], _hmac_otp(recsive_otp))


def clear_otp_session():
    session.pop('otp_hmac', None)
    session.pop('otp_expires_at', None)
    session.pop('otp_attempts', None)

def send_otp_sms(mobile, code):
    """Send OTP via IPPanel SMS service."""
    data = {
        "op": "pattern",
        "user": IPPANEL_USER,
        "pass": IPPANEL_PASS,
        "fromNum": FROM_NUMBER,
        "toNum": mobile,
        "patternCode": PATTERN_CODE,
        "inputData": [{"code": str(code)}]
    }

    try:
        response = requests.post(IPPANEL_URL, json=data, timeout=5)
        return response.json()
    except Exception as e:
        return {"error": str(e)}
    




def send_email_otp(email, code, language='fa'):
    """ارسال کد تایید با Resend"""
    
    # تنظیم کلید API
    resend.api_key = os.environ.get("RESEND_API_KEY")
    
    # محتوای ایمیل فارسی
    if language == 'fa':
        html_body = f"""
        <div style="font-family: Tahoma; text-align: right; direction: rtl;padding: 20px;">
            <div style="max-width: 500px; background: white; padding: 25px; border-radius: 12px; margin: auto;">
                <h2 style="color: #1a237e;">کد تأیید دستیار هوشمند تکسورا</h2>
                <p>سلام </p>
                <p>کد تأیید شما برای ورود به سامانه:</p>
                <p style="font-size: 26px; background: #e3f2fd; padding: 10px; text-align: center;">
                    <strong>{code}</strong>
                </p>
                <p>این کد تا ۵ دقیقه معتبر است.</p>
                <hr>
                <p style="text-align: center;">با احترام،<br>تیم دستیار هوشمند تکسورا</p>
            </div>
        </div>
        """
        
        subject = "کد تأیید دستیار هوشمند تکسورا"
    
    # محتوای ایمیل انگلیسی
    else:
        html_body = f"""
        <div style="font-family: Arial; padding: 20px;">
            <div style="max-width: 500px; background: white; padding: 25px; border-radius: 12px; margin: auto;">
                <h2 style="color: #1a237e;">Texora Verification Code</h2>
                <p>Hello </p>
                <p>Your verification code:</p>
                <p style="font-size: 26px; background: #e3f2fd; padding: 10px; text-align: center;">
                    <strong>{code}</strong>
                </p>
                <p>This code is valid for 5 minutes.</p>
                <hr>
                <p style="text-align: center;">Best regards,<br>Texora Smart Assistant Team</p>
            </div>
        </div>
        """
        
        subject = "Texora Verification Code"
    
    # ارسال ایمیل
    try:
        



        print('Start Resend')
        
        resend.Emails.send({
            "from": "Texora Smart Assistant <noreply@aitexora.com>",
            "headers": {
                "Reply-To": "support@aitexora.com"
            },
            "to": email,
            "subject": subject,
            "text": f"Your verification code is {code}. This code is valid for 5 minutes."
        })
        
        print('Send')
        
        return f"send email "
    
    except Exception as e:
        return f"Error in send email : {e}"
        
        
        
