"""Custom license dialogs — modern dark theme.

Supports PySide6 (preferred), Tkinter (fallback), console (last resort).
"""

import sys
from pathlib import Path


def _try_pyside6_license_dialog(
    title: str = "License Activation",
    logo_path: str | None = None,
) -> str | None:
    """Modern dark PySide6 dialog for license key entry."""
    try:
        from PySide6.QtWidgets import (
            QApplication, QDialog, QVBoxLayout, QHBoxLayout,
            QLabel, QLineEdit, QPushButton, QGraphicsDropShadowEffect,
        )
        from PySide6.QtCore import Qt
        from PySide6.QtGui import QFont, QPixmap, QIcon, QColor
    except ImportError:
        return None  # signal caller to try next method

    app = QApplication.instance()
    if app is None:
        app = QApplication(sys.argv)

    class LicenseDialog(QDialog):
        def __init__(self):
            super().__init__()
            self.result_key = None
            self._setup_ui(title, logo_path)

        def _setup_ui(self, title: str, logo_path: str | None):
            self.setWindowTitle(title)
            self.setFixedSize(420, 320)
            self.setWindowFlags(
                Qt.WindowType.Dialog
                | Qt.WindowType.WindowCloseButtonHint
            )

            # Dark stylesheet
            self.setStyleSheet("""
                QDialog {
                    background-color: #1e1e2e;
                    border: 1px solid #313244;
                    border-radius: 12px;
                }
                QLabel {
                    color: #cdd6f4;
                    background: transparent;
                }
                QLineEdit {
                    background-color: #313244;
                    color: #cdd6f4;
                    border: 2px solid #45475a;
                    border-radius: 8px;
                    padding: 10px 14px;
                    font-size: 16px;
                    font-family: 'Consolas', 'Courier New', monospace;
                    letter-spacing: 2px;
                    selection-background-color: #585b70;
                }
                QLineEdit:focus {
                    border: 2px solid #89b4fa;
                }
                QLineEdit:hover {
                    border: 2px solid #585b70;
                }
                QPushButton {
                    border-radius: 8px;
                    padding: 10px 24px;
                    font-size: 13px;
                    font-weight: bold;
                    border: none;
                }
                QPushButton#activate {
                    background-color: #89b4fa;
                    color: #1e1e2e;
                }
                QPushButton#activate:hover {
                    background-color: #b4d0fb;
                }
                QPushButton#activate:pressed {
                    background-color: #74a8f7;
                }
                QPushButton#activate:disabled {
                    background-color: #45475a;
                    color: #6c7086;
                }
                QPushButton#cancel {
                    background-color: #313244;
                    color: #a6adc8;
                }
                QPushButton#cancel:hover {
                    background-color: #45475a;
                }
            """)

            layout = QVBoxLayout(self)
            layout.setContentsMargins(32, 28, 32, 24)
            layout.setSpacing(0)

            # Logo
            if logo_path and Path(logo_path).exists():
                logo_label = QLabel()
                pixmap = QPixmap(logo_path)
                scaled = pixmap.scaled(
                    64, 64,
                    Qt.AspectRatioMode.KeepAspectRatio,
                    Qt.TransformationMode.SmoothTransformation,
                )
                logo_label.setPixmap(scaled)
                logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                layout.addWidget(logo_label)
                layout.addSpacing(12)
            else:
                # Shield icon via text
                icon_label = QLabel("\U0001f6e1")
                icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                icon_font = QFont()
                icon_font.setPointSize(28)
                icon_label.setFont(icon_font)
                layout.addWidget(icon_label)
                layout.addSpacing(8)

            # Title
            title_label = QLabel(title)
            title_font = QFont()
            title_font.setPointSize(16)
            title_font.setBold(True)
            title_label.setFont(title_font)
            title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            title_label.setStyleSheet("color: #cdd6f4;")
            layout.addWidget(title_label)
            layout.addSpacing(20)

            # Subtitle
            sub_label = QLabel("Enter your license key to activate")
            sub_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            sub_label.setStyleSheet("color: #6c7086; font-size: 12px;")
            layout.addWidget(sub_label)
            layout.addSpacing(16)

            # Input
            self.key_input = QLineEdit()
            self.key_input.setPlaceholderText("XXXX-XXXX-XXXX-XXXX")
            self.key_input.setMaxLength(19)
            self.key_input.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.key_input.textChanged.connect(self._on_text_changed)
            self.key_input.returnPressed.connect(self._on_activate)
            layout.addWidget(self.key_input)
            layout.addSpacing(24)

            # Buttons
            btn_layout = QHBoxLayout()
            btn_layout.setSpacing(12)

            self.cancel_btn = QPushButton("Cancel")
            self.cancel_btn.setObjectName("cancel")
            self.cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor)
            self.cancel_btn.clicked.connect(self.reject)

            self.activate_btn = QPushButton("Activate")
            self.activate_btn.setObjectName("activate")
            self.activate_btn.setCursor(Qt.CursorShape.PointingHandCursor)
            self.activate_btn.setEnabled(False)
            self.activate_btn.clicked.connect(self._on_activate)

            # Glow effect on activate button
            glow = QGraphicsDropShadowEffect()
            glow.setBlurRadius(20)
            glow.setColor(QColor("#89b4fa"))
            glow.setOffset(0, 0)
            self.activate_btn.setGraphicsEffect(glow)

            btn_layout.addWidget(self.cancel_btn)
            btn_layout.addWidget(self.activate_btn)
            layout.addLayout(btn_layout)

        def _on_text_changed(self, text: str):
            # Auto-insert dashes
            clean = text.replace("-", "").upper()
            if len(clean) > 16:
                clean = clean[:16]
            # Format as XXXX-XXXX-XXXX-XXXX
            parts = [clean[i:i+4] for i in range(0, len(clean), 4)]
            formatted = "-".join(parts)
            if formatted != text:
                self.key_input.blockSignals(True)
                self.key_input.setText(formatted)
                self.key_input.setCursorPosition(len(formatted))
                self.key_input.blockSignals(False)
            # Enable activate when complete
            self.activate_btn.setEnabled(len(clean) == 16)

        def _on_activate(self):
            if self.activate_btn.isEnabled():
                self.result_key = self.key_input.text().strip().upper()
                self.accept()

    dlg = LicenseDialog()
    dlg.key_input.setFocus()
    if dlg.exec() == QDialog.DialogCode.Accepted and dlg.result_key:
        return dlg.result_key
    return None


def _try_pyside6_error_dialog(message: str, title: str = "License Error") -> bool:
    """Modern dark PySide6 error dialog. Returns True if shown."""
    try:
        from PySide6.QtWidgets import (
            QApplication, QDialog, QVBoxLayout, QLabel, QPushButton,
        )
        from PySide6.QtCore import Qt
        from PySide6.QtGui import QFont
    except ImportError:
        return False

    app = QApplication.instance()
    if app is None:
        app = QApplication(sys.argv)

    class ErrorDialog(QDialog):
        def __init__(self):
            super().__init__()
            self.setWindowTitle(title)
            self.setFixedSize(400, 220)
            self.setWindowFlags(
                Qt.WindowType.Dialog
                | Qt.WindowType.WindowCloseButtonHint
            )
            self.setStyleSheet("""
                QDialog {
                    background-color: #1e1e2e;
                    border: 1px solid #313244;
                }
                QLabel { color: #cdd6f4; background: transparent; }
                QPushButton {
                    background-color: #f38ba8;
                    color: #1e1e2e;
                    border: none;
                    border-radius: 8px;
                    padding: 10px 32px;
                    font-size: 13px;
                    font-weight: bold;
                }
                QPushButton:hover { background-color: #f5a0b8; }
            """)

            layout = QVBoxLayout(self)
            layout.setContentsMargins(32, 28, 32, 24)
            layout.setSpacing(0)

            # Error icon
            icon = QLabel("\u274c")
            icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
            icon_font = QFont()
            icon_font.setPointSize(28)
            icon.setFont(icon_font)
            layout.addWidget(icon)
            layout.addSpacing(12)

            # Title
            title_label = QLabel(title)
            title_font = QFont()
            title_font.setPointSize(14)
            title_font.setBold(True)
            title_label.setFont(title_font)
            title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            layout.addWidget(title_label)
            layout.addSpacing(8)

            # Message
            msg_label = QLabel(message)
            msg_label.setWordWrap(True)
            msg_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            msg_label.setStyleSheet("color: #a6adc8; font-size: 12px;")
            layout.addWidget(msg_label)
            layout.addSpacing(20)

            # OK button
            ok_btn = QPushButton("OK")
            ok_btn.setCursor(Qt.CursorShape.PointingHandCursor)
            ok_btn.clicked.connect(self.accept)
            ok_btn.setFixedWidth(120)
            layout.addWidget(ok_btn, alignment=Qt.AlignmentFlag.AlignCenter)

    dlg = ErrorDialog()
    dlg.exec()
    return True


# ── Public API ──────────────────────────────────────────────

def prompt_license_key(
    title: str = "License Activation",
    logo_path: str | None = None,
) -> str | None:
    """Show license key dialog. Returns key string or None if cancelled."""
    print("[CGT] _dialogs.py loaded — trying PySide6 dialog...", flush=True)
    # Try PySide6 first
    try:
        result = _try_pyside6_license_dialog(title, logo_path)
    except Exception as e:
        print(f"[CGT] PySide6 dialog EXCEPTION: {type(e).__name__}: {e}", flush=True)
        result = None
    if result is not None:
        return result

    # If PySide6 returned None but was available, user cancelled
    try:
        import PySide6  # noqa: F401
        return None  # PySide6 is available, user cancelled
    except ImportError:
        pass

    # Try Tkinter
    try:
        import tkinter as tk
        from tkinter import simpledialog
        root = tk.Tk()
        root.withdraw()
        text = simpledialog.askstring(
            "License Required",
            "Enter your license key (XXXX-XXXX-XXXX-XXXX):",
            parent=root,
        )
        root.destroy()
        if text and text.strip():
            return text.strip()
        return None
    except ImportError:
        pass

    # Console fallback
    try:
        text = input("Enter license key: ").strip()
        return text if text else None
    except EOFError:
        return None


def show_error_and_exit(message: str):
    """Show error dialog and sys.exit(1)."""
    if _try_pyside6_error_dialog(message):
        sys.exit(1)

    # Try Tkinter
    try:
        import tkinter as tk
        from tkinter import messagebox
        root = tk.Tk()
        root.withdraw()
        messagebox.showerror("License Error", message)
        root.destroy()
        sys.exit(1)
    except ImportError:
        pass

    print(f"LICENSE ERROR: {message}", file=sys.stderr)
    sys.exit(1)
