"""Helper functions for the bot."""

import random
import string
from datetime import datetime
import jdatetime


def generate_referral_code(length: int = 8) -> str:
    """Generate a unique referral code."""
    return "".join(random.choices(string.ascii_uppercase + string.digits, k=length))


def format_score(score: int) -> str:
    """Format score with Persian number formatting."""
    persian_numbers = {
        "0": "۰", "1": "۱", "2": "۲", "3": "۳", "4": "۴",
        "5": "۵", "6": "۶", "7": "۷", "8": "۸", "9": "۹"
    }
    return "".join(persian_numbers.get(c, c) for c in str(score))


def gregorian_to_persian(dt: datetime) -> str:
    """Convert Gregorian datetime to Persian (Jalali) format.
    
    Returns format: ۱۴۰۴/۰۳/۲۴ ۲۰:۵۰ (YYYY/MM/DD HH:MM with Persian digits)
    """
    if not dt:
        return ""
    persian_dt = jdatetime.datetime.fromgregorian(datetime=dt)
    # استفاده از اعداد فارسی
    year = format_score(persian_dt.year)
    month = format_score(persian_dt.month)
    day = format_score(persian_dt.day)
    hour = format_score(persian_dt.hour)
    minute = format_score(persian_dt.minute)
    return f"{year}/{month}/{day} {hour}:{minute}"


def persian_to_gregorian(persian_date_str: str) -> datetime:
    """Convert Persian date string to Gregorian datetime.
    
    Expects format: YYYY/MM/DD HH:MM (with Persian or English digits)
    Example: 1404/03/24 20:50 or ۱۴۰۴/۰۳/۲۴ ۲۰:۵۰
    """
    # تبدیل اعداد فارسی به انگلیسی
    persian_digits = "۰۱۲۳۴۵۶۷۸۹"
    english_digits = "0123456789"
    translation_table = str.maketrans(persian_digits, english_digits)
    normalized = persian_date_str.translate(translation_table)
    
    # جدا کردن تاریخ و ساعت
    parts = normalized.split()
    if len(parts) != 2:
        raise ValueError("فرمت تاریخ باید شامل تاریخ و ساعت باشد: YYYY/MM/DD HH:MM")
    
    date_part, time_part = parts
    year, month, day = map(int, date_part.split('/'))
    hour, minute = map(int, time_part.split(':'))
    
    # تبدیل به میلادی
    persian_dt = jdatetime.datetime(year, month, day, hour, minute)
    return persian_dt.togregorian()


def format_match_display(match: dict) -> str:
    """Format match for display in messages."""
    team1 = match.get("team1", "")
    team2 = match.get("team2", "")
    team1_flag = match.get("team1_flag", "")
    team2_flag = match.get("team2_flag", "")
    match_time = match.get("match_time", "")
    
    time_str = gregorian_to_persian(match_time) if match_time else ""
    return f"{team1_flag} {team1} vs {team2} {team2_flag}\n{time_str}"