#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
================================================================================
Генератор игральных карт для игры 21 Очко
================================================================================
Создает PNG-изображения всех 52 карт и рубашки
================================================================================
"""

import os
from PIL import Image, ImageDraw, ImageFont

# Создаем папку для карт
cards_dir = os.path.join(os.path.dirname(__file__), "cards")
os.makedirs(cards_dir, exist_ok=True)

# Цвета
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (196, 30, 58)      # #C41E3A
DARK_BLUE = (44, 62, 80) # #2C3E50
GOLD = (243, 156, 18)    # #F39C12
BLUE_GRAY = (52, 73, 94) # #34495E

# Масти
SUITS = [
    {'symbol': '♥', 'name': 'hearts', 'color': RED},
    {'symbol': '♦', 'name': 'diamonds', 'color': RED},
    {'symbol': '♣', 'name': 'clubs', 'color': DARK_BLUE},
    {'symbol': '♠', 'name': 'spades', 'color': DARK_BLUE}
]

# Значения
RANKS = [
    {'short': '2', 'full': '2', 'file': '2'},
    {'short': '3', 'full': '3', 'file': '3'},
    {'short': '4', 'full': '4', 'file': '4'},
    {'short': '5', 'full': '5', 'file': '5'},
    {'short': '6', 'full': '6', 'file': '6'},
    {'short': '7', 'full': '7', 'file': '7'},
    {'short': '8', 'full': '8', 'file': '8'},
    {'short': '9', 'full': '9', 'file': '9'},
    {'short': '10', 'full': '10', 'file': '10'},
    {'short': 'В', 'full': 'Валет', 'file': 'jack'},
    {'short': 'Д', 'full': 'Дама', 'file': 'queen'},
    {'short': 'К', 'full': 'Король', 'file': 'king'},
    {'short': 'Т', 'full': 'Туз', 'file': 'ace'}
]

# Размер карты
CARD_WIDTH = 100
CARD_HEIGHT = 140
CORNER_RADIUS = 8

def rounded_rectangle(draw, rect, radius, fill=None, outline=None, width=1):
    """Рисует прямоугольник со скругленными углами"""
    x1, y1, x2, y2 = rect
    draw.rectangle([x1+radius, y1, x2-radius, y2], fill=fill, outline=outline, width=width)
    draw.rectangle([x1, y1+radius, x2, y2-radius], fill=fill, outline=outline, width=width)
    draw.pieslice([x1, y1, x1+2*radius, y1+2*radius], 180, 270, fill=fill, outline=outline, width=width)
    draw.pieslice([x2-2*radius, y1, x2, y1+2*radius], 270, 360, fill=fill, outline=outline, width=width)
    draw.pieslice([x1, y2-2*radius, x1+2*radius, y2], 90, 180, fill=fill, outline=outline, width=width)
    draw.pieslice([x2-2*radius, y2-2*radius, x2, y2], 0, 90, fill=fill, outline=outline, width=width)

def generate_card_back():
    """Генерирует рубашку карты"""
    img = Image.new('RGB', (CARD_WIDTH, CARD_HEIGHT), color=WHITE)
    draw = ImageDraw.Draw(img)
    
    # Фон с градиентом
    for y in range(CARD_HEIGHT):
        color_value = int(52 + (y / CARD_HEIGHT) * 40)
        color = (color_value, color_value + 20, color_value + 40)
        draw.line([(0, y), (CARD_WIDTH, y)], fill=color)
    
    # Скругленный прямоугольник
    rounded_rectangle(draw, [2, 2, CARD_WIDTH-2, CARD_HEIGHT-2], CORNER_RADIUS, outline=GOLD, width=2)
    
    # Узор - ромбики
    for x in range(10, CARD_WIDTH-10, 15):
        for y in range(10, CARD_HEIGHT-10, 15):
            draw.polygon([(x, y-3), (x+3, y), (x, y+3), (x-3, y)], fill=(100, 100, 100, 30))
    
    # Центральный символ
    try:
        font = ImageFont.truetype("arial.ttf", 40)
    except:
        font = ImageFont.load_default()
    
    draw.text((30, 50), "🃏", font=font, fill=GOLD)
    
    img.save(os.path.join(cards_dir, "back.png"))
    print("✓ Сгенерирована рубашка карты")

def generate_card(rank, suit):
    """Генерирует одну карту"""
    img = Image.new('RGB', (CARD_WIDTH, CARD_HEIGHT), color=WHITE)
    draw = ImageDraw.Draw(img)
    
    # Скругленный прямоугольник
    rounded_rectangle(draw, [2, 2, CARD_WIDTH-2, CARD_HEIGHT-2], CORNER_RADIUS, outline=BLACK, width=1)
    
    # Загружаем шрифты
    try:
        small_font = ImageFont.truetype("arial.ttf", 16)
        large_font = ImageFont.truetype("arial.ttf", 32)
    except:
        small_font = ImageFont.load_default()
        large_font = ImageFont.load_default()
    
    color = suit['color']
    
    # Верхний левый угол
    draw.text((8, 5), rank['short'], font=small_font, fill=color)
    draw.text((8, 22), suit['symbol'], font=small_font, fill=color)
    
    # Нижний правый угол (перевернутый)
    draw.text((CARD_WIDTH-25, CARD_HEIGHT-35), rank['short'], font=small_font, fill=color)
    draw.text((CARD_WIDTH-25, CARD_HEIGHT-18), suit['symbol'], font=small_font, fill=color)
    
    # Центральный символ
    if rank['short'] in ['В', 'Д', 'К', 'Т']:
        # Для картинок рисуем букву и масть
        draw.text((CARD_WIDTH//2-15, CARD_HEIGHT//2-20), rank['full'][0], font=large_font, fill=color)
        draw.text((CARD_WIDTH//2-10, CARD_HEIGHT//2+5), suit['symbol'], font=large_font, fill=color)
    else:
        # Для числовых карт рисуем число и масть
        draw.text((CARD_WIDTH//2-15, CARD_HEIGHT//2-20), rank['short'], font=large_font, fill=color)
        draw.text((CARD_WIDTH//2-10, CARD_HEIGHT//2+5), suit['symbol'], font=large_font, fill=color)
    
    filename = f"{rank['file']}_of_{suit['name']}.png"
    img.save(os.path.join(cards_dir, filename))
    print(f"✓ Сгенерирована карта: {rank['full']} {suit['symbol']}")

def generate_all_cards():
    """Генерирует все карты"""
    print("🎴 Генерация игральных карт...")
    print("=" * 50)
    
    generate_card_back()
    
    for suit in SUITS:
        for rank in RANKS:
            generate_card(rank, suit)
    
    print("=" * 50)
    print(f"✅ Сгенерировано 53 карты в папку: {cards_dir}")

if __name__ == "__main__":
    generate_all_cards()