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

"""
================================================================================
Модуль: 21 Очко для дальнобойщика
================================================================================
Карточная игра для скоротания времени в ожидании загрузки/разгрузки
================================================================================
"""

import os
import random
from datetime import datetime

from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QPushButton, QGroupBox, QFrame, QMainWindow, 
    QApplication, QMessageBox, QDialog, QDialogButtonBox,
    QTextBrowser
)
from PyQt5.QtCore import Qt, QTimer, pyqtSignal
from PyQt5.QtGui import QFont, QPixmap, QIcon


class TwentyOneModule:
    """Класс модуля для ModuleManager"""
    
    display_name = "🎲 21 Очко"
    description = "Карточная игра для дальнобойщиков"
    menu_category = "games"
    
    def __init__(self, main_window):
        self.main_window = main_window
        self.widget = None
        self.window = None
    
    def run(self):
        """Запуск модуля — открывает интерфейс в отдельном окне"""
        self.widget = TwentyOneWidget(self.main_window, self)
        
        self.window = QMainWindow()
        self.window.setWindowTitle(f"{self.display_name} - РейсМастер")
        self.window.setWindowIcon(self.main_window.windowIcon())
        self.window.setCentralWidget(self.widget)
        self.window.resize(1000, 750)
        self.window.setMinimumSize(900, 650)
        self.window.show()


class HelpDialog(QDialog):
    """Диалог с правилами игры"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("📚 Правила игры 21 Очко")
        self.setMinimumSize(600, 500)
        self.setup_ui()
    
    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        
        title = QLabel("🎲 ПРАВИЛА ИГРЫ 21 ОЧКО")
        title.setStyleSheet("""
            font-size: 20px;
            font-weight: bold;
            color: white;
            background-color: #1976D2;
            padding: 12px;
            border-radius: 8px;
        """)
        title.setAlignment(Qt.AlignCenter)
        layout.addWidget(title)
        
        text = QTextBrowser()
        text.setStyleSheet("""
            QTextBrowser {
                background-color: #f9f9f9;
                border: 2px solid #c0c0c0;
                border-radius: 8px;
                padding: 15px;
                font-size: 11pt;
                line-height: 1.6;
            }
        """)
        
        html = """
        <style>
            h2 { color: #1976D2; margin-top: 15px; }
            .card { display: inline-block; background: white; border: 1px solid black; 
                    border-radius: 3px; padding: 2px 5px; margin: 2px; font-weight: bold; }
            .red { color: #C41E3A; }
            .black { color: #2C3E50; }
        </style>
        
        <h2>🎯 Цель игры</h2>
        <p>Набрать 21 очко или как можно ближе. Перебор (>21) — проигрыш.</p>
        
        <h2>🃏 Значение карт</h2>
        <ul>
            <li><span class='card black'>2♠</span>...<span class='card red'>10♥</span> — по номиналу</li>
            <li><span class='card black'>Валет♣</span> — <b>2 очка</b></li>
            <li><span class='card red'>Дама♦</span> — <b>3 очка</b></li>
            <li><span class='card black'>Король♠</span> — <b>4 очка</b></li>
            <li><span class='card red'>Туз♥</span> — <b>11 очков</b></li>
        </ul>
        
        <h2>🎮 Как играть</h2>
        <ol>
            <li><b>ЕЩЁ</b> — взять карту</li>
            <li><b>ХВАТИТ</b> — закончить ход</li>
            <li>Дилер берет до 17 очков</li>
        </ol>
        """
        
        text.setHtml(html)
        layout.addWidget(text)
        
        btn = QDialogButtonBox(QDialogButtonBox.Ok)
        btn.accepted.connect(self.accept)
        layout.addWidget(btn)


class Card:
    """Класс игральной карты"""
    
    SUITS = {
        '♥': {'name': 'hearts', 'color': '#C41E3A'},
        '♦': {'name': 'diamonds', 'color': '#C41E3A'},
        '♣': {'name': 'clubs', 'color': '#2C3E50'},
        '♠': {'name': 'spades', 'color': '#2C3E50'}
    }
    
    RANKS = {
        2: ('2', '2'), 3: ('3', '3'), 4: ('4', '4'), 5: ('5', '5'),
        6: ('6', '6'), 7: ('7', '7'), 8: ('8', '8'), 9: ('9', '9'),
        10: ('10', '10'), 11: ('В', 'jack'), 12: ('Д', 'queen'),
        13: ('К', 'king'), 14: ('Т', 'ace')
    }
    
    POINTS = {2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:2,12:3,13:4,14:11}
    
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank
        self.points = self.POINTS[rank]
        self.short = self.RANKS[rank][0]
        self.file = self.RANKS[rank][1]
        self.is_hidden = False
    
    def filename(self):
        if self.is_hidden:
            return "back.png"
        return f"{self.file}_of_{self.SUITS[self.suit]['name']}.png"


class Deck:
    """Колода карт"""
    
    def __init__(self):
        self.cards = []
        for suit in Card.SUITS:
            for rank in range(2, 15):
                self.cards.append(Card(suit, rank))
        self.shuffle()
    
    def shuffle(self):
        random.shuffle(self.cards)
    
    def draw(self):
        if not self.cards:
            self.__init__()
        return self.cards.pop(0)


class CardWidget(QLabel):
    """Виджет карты с изображением"""
    
    def __init__(self, card, parent=None):
        super().__init__(parent)
        self.card = card
        self.setFixedSize(100, 140)
        self.setAlignment(Qt.AlignCenter)
        self.setScaledContents(True)
        self.update_image()
    
    def update_image(self):
        path = os.path.join(os.path.dirname(__file__), "cards", self.card.filename())
        if os.path.exists(path):
            pixmap = QPixmap(path)
            self.setPixmap(pixmap.scaled(100, 140, Qt.KeepAspectRatio, Qt.SmoothTransformation))
    
    def set_card(self, card):
        self.card = card
        self.update_image()


class TwentyOneWidget(QWidget):
    """Основной интерфейс игры"""
    
    def __init__(self, main_window, module):
        super().__init__()
        self.main_window = main_window
        self.module = module
        self.deck = Deck()
        self.player_cards = []
        self.dealer_cards = []
        self.player_wins = 0
        self.dealer_wins = 0
        self.draws = 0
        self.game_state = "betting"
        self.setup_ui()
        self.new_game()
    
    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # Верхняя панель
        top = QHBoxLayout()
        title = QLabel("🎲 21 ОЧКО ДЛЯ ДАЛЬНОБОЙЩИКА")
        title.setStyleSheet("""
            font-size: 24px; font-weight: bold; color: white;
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #1976D2, stop:1 #2E7D32);
            padding: 15px; border-radius: 10px;
        """)
        title.setAlignment(Qt.AlignCenter)
        top.addWidget(title)
        
        rules_btn = QPushButton("📚 Правила")
        rules_btn.setFixedSize(120, 40)
        rules_btn.setStyleSheet("""
            QPushButton { background-color: #F39C12; color: white; border-radius: 5px;
                         font-size: 12pt; font-weight: bold; }
            QPushButton:hover { background-color: #E67E22; }
        """)
        rules_btn.clicked.connect(self.show_rules)
        top.addWidget(rules_btn)
        layout.addLayout(top)
        
        # Счет
        score = QHBoxLayout()
        self.player_score = QLabel(f"Игрок: 0")
        self.player_score.setStyleSheet("font-size: 18px; font-weight: bold; color: #1976D2;")
        self.draws_label = QLabel(f"Ничьи: 0")
        self.draws_label.setStyleSheet("font-size: 18px; font-weight: bold; color: #F39C12;")
        self.dealer_score = QLabel(f"Дилер: 0")
        self.dealer_score.setStyleSheet("font-size: 18px; font-weight: bold; color: #C41E3A;")
        
        for label in [self.player_score, self.draws_label, self.dealer_score]:
            label.setAlignment(Qt.AlignCenter)
            label.setFixedHeight(40)
            score.addWidget(label)
        layout.addLayout(score)
        
        # Дилер
        dealer_group = QGroupBox("👤 ДИЛЕР")
        dealer_group.setStyleSheet("""
            QGroupBox { font-size: 16px; font-weight: bold; border: 2px solid #C41E3A;
                       border-radius: 10px; margin-top: 15px; padding-top: 20px;
                       background-color: #FFF5F5; }
            QGroupBox::title { subcontrol-origin: margin; left: 20px; padding: 0 15px;
                               color: #C41E3A; background: white; border-radius: 5px; }
        """)
        dealer_layout = QVBoxLayout(dealer_group)
        
        self.dealer_cards_layout = QHBoxLayout()
        self.dealer_cards_layout.setSpacing(10)
        self.dealer_cards_layout.addStretch()
        dealer_layout.addLayout(self.dealer_cards_layout)
        
        self.dealer_points = QLabel("🎴 Очки: ?")
        self.dealer_points.setStyleSheet("font-size: 16px; font-weight: bold; color: #C41E3A;")
        self.dealer_points.setAlignment(Qt.AlignCenter)
        dealer_layout.addWidget(self.dealer_points)
        layout.addWidget(dealer_group)
        
        # Игрок
        player_group = QGroupBox("👤 ИГРОК (ВЫ)")
        player_group.setStyleSheet("""
            QGroupBox { font-size: 16px; font-weight: bold; border: 2px solid #1976D2;
                       border-radius: 10px; margin-top: 15px; padding-top: 20px;
                       background-color: #F0F7FF; }
            QGroupBox::title { subcontrol-origin: margin; left: 20px; padding: 0 15px;
                               color: #1976D2; background: white; border-radius: 5px; }
        """)
        player_layout = QVBoxLayout(player_group)
        
        self.player_cards_layout = QHBoxLayout()
        self.player_cards_layout.setSpacing(10)
        self.player_cards_layout.addStretch()
        player_layout.addLayout(self.player_cards_layout)
        
        self.player_points = QLabel("🎴 Очки: 0")
        self.player_points.setStyleSheet("font-size: 16px; font-weight: bold; color: #1976D2;")
        self.player_points.setAlignment(Qt.AlignCenter)
        player_layout.addWidget(self.player_points)
        layout.addWidget(player_group)
        
        # Сообщение
        self.message = QLabel("🎮 Нажмите 'Новая игра' для начала")
        self.message.setStyleSheet("""
            font-size: 14px; font-weight: bold; color: #2C3E50;
            background: #F5F5F5; padding: 12px; border-radius: 8px;
            border: 2px solid #BDC3C7;
        """)
        self.message.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.message)
        
        # Кнопки
        buttons = QHBoxLayout()
        buttons.addStretch()
        
        self.hit_btn = QPushButton("🎴 ЕЩЁ")
        self.hit_btn.setFixedSize(120, 50)
        self.hit_btn.setStyleSheet("""
            QPushButton { background: #1976D2; color: white; border-radius: 8px;
                         font-size: 16px; font-weight: bold; }
            QPushButton:hover { background: #1565C0; }
            QPushButton:disabled { background: #B0BEC5; }
        """)
        self.hit_btn.clicked.connect(self.hit)
        buttons.addWidget(self.hit_btn)
        
        self.stand_btn = QPushButton("✋ ХВАТИТ")
        self.stand_btn.setFixedSize(120, 50)
        self.stand_btn.setStyleSheet("""
            QPushButton { background: #FFA000; color: white; border-radius: 8px;
                         font-size: 16px; font-weight: bold; }
            QPushButton:hover { background: #FF8F00; }
            QPushButton:disabled { background: #B0BEC5; }
        """)
        self.stand_btn.clicked.connect(self.stand)
        buttons.addWidget(self.stand_btn)
        
        self.new_btn = QPushButton("🔄 НОВАЯ ИГРА")
        self.new_btn.setFixedSize(150, 50)
        self.new_btn.setStyleSheet("""
            QPushButton { background: #2E7D32; color: white; border-radius: 8px;
                         font-size: 16px; font-weight: bold; }
            QPushButton:hover { background: #1B5E20; }
        """)
        self.new_btn.clicked.connect(self.new_game)
        buttons.addWidget(self.new_btn)
        
        layout.addLayout(buttons)
    
    def show_rules(self):
        HelpDialog(self).exec_()
    
    def clear_layout(self, layout):
        while layout.count():
            item = layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()
    
    def update_display(self):
        # Очищаем и перестраиваем карты
        self.clear_layout(self.dealer_cards_layout)
        self.clear_layout(self.player_cards_layout)
        
        for card in self.dealer_cards:
            self.dealer_cards_layout.addWidget(CardWidget(card))
        self.dealer_cards_layout.addStretch()
        
        for card in self.player_cards:
            self.player_cards_layout.addWidget(CardWidget(card))
        self.player_cards_layout.addStretch()
        
        # Обновляем очки
        player_pts = self.calc_points(self.player_cards)
        self.player_points.setText(f"🎴 Очки: {player_pts}")
        
        if self.game_state in ["player_turn", "betting"]:
            self.dealer_points.setText("🎴 Очки: ?")
        else:
            dealer_pts = self.calc_points(self.dealer_cards)
            self.dealer_points.setText(f"🎴 Очки: {dealer_pts}")
        
        # Обновляем счет
        self.player_score.setText(f"Игрок: {self.player_wins}")
        self.dealer_score.setText(f"Дилер: {self.dealer_wins}")
        self.draws_label.setText(f"Ничьи: {self.draws}")
        
        # Кнопки
        self.hit_btn.setEnabled(self.game_state == "player_turn")
        self.stand_btn.setEnabled(self.game_state == "player_turn")
    
    def calc_points(self, cards):
        pts = 0
        aces = 0
        for card in cards:
            if not card.is_hidden:
                if card.rank == 14:
                    aces += 1
                else:
                    pts += card.points
        for _ in range(aces):
            pts += 11 if pts + 11 <= 21 else 1
        return pts
    
    def hit(self):
        card = self.deck.draw()
        self.player_cards.append(card)
        pts = self.calc_points(self.player_cards)
        
        if pts > 21:
            self.game_state = "game_over"
            self.dealer_wins += 1
            self.message.setText(f"😵 ПЕРЕБОР! {pts} очков. Дилер победил.")
            for card in self.dealer_cards:
                card.is_hidden = False
        else:
            self.message.setText(f"У вас {pts} очков. Берём ещё?")
        
        self.update_display()
    
    def stand(self):
        self.game_state = "dealer_turn"
        for card in self.dealer_cards:
            card.is_hidden = False
        self.message.setText("🎲 Ход дилера...")
        self.update_display()
        QTimer.singleShot(500, self.dealer_turn)
    
    def dealer_turn(self):
        dealer_pts = self.calc_points(self.dealer_cards)
        player_pts = self.calc_points(self.player_cards)
        
        while dealer_pts < 17:
            card = self.deck.draw()
            self.dealer_cards.append(card)
            dealer_pts = self.calc_points(self.dealer_cards)
            self.update_display()
            QApplication.processEvents()
            QTimer.singleShot(300, lambda: None)
        
        self.game_state = "game_over"
        
        if dealer_pts > 21:
            self.player_wins += 1
            self.message.setText(f"🎉 ДИЛЕР ПЕРЕБРАЛ! Вы победили! ({player_pts}:{dealer_pts})")
        elif dealer_pts > player_pts:
            self.dealer_wins += 1
            self.message.setText(f"😢 Дилер победил ({player_pts}:{dealer_pts})")
        elif dealer_pts < player_pts:
            self.player_wins += 1
            self.message.setText(f"🎉 Вы победили! ({player_pts}:{dealer_pts})")
        else:
            self.draws += 1
            self.message.setText(f"🤝 Ничья! ({player_pts}:{dealer_pts})")
        
        self.update_display()
    
    def new_game(self):
        self.deck = Deck()
        self.player_cards = []
        self.dealer_cards = []
        
        # Раздаем
        self.player_cards.append(self.deck.draw())
        self.player_cards.append(self.deck.draw())
        
        card1 = self.deck.draw()
        card1.is_hidden = False
        self.dealer_cards.append(card1)
        
        card2 = self.deck.draw()
        card2.is_hidden = True
        self.dealer_cards.append(card2)
        
        # Проверка на блэкджек
        if self.calc_points(self.player_cards) == 21:
            self.game_state = "game_over"
            self.player_wins += 1
            self.message.setText("🎉 БЛЭКДЖЕК! Вы победили!")
            for card in self.dealer_cards:
                card.is_hidden = False
        else:
            self.game_state = "player_turn"
            self.message.setText("🎮 Ваш ход! Берём карту?")
        
        self.update_display()