"""Windows activation dialog for MuraveyChina license system (PyQt6).

Shows a modal dialog when no valid session is found.
Provides token entry, purchase button, and activation flow.
"""

from __future__ import annotations

import logging
import sys
import webbrowser

PURCHASE_PAGE_URL = "https://whop.com/checkout/plan_YFqvqKJproMsR"

logger = logging.getLogger(__name__)


class ActivationDialog:
    """Modal activation dialog for Windows using PyQt6."""

    def __init__(self, license_manager) -> None:
        self._mgr = license_manager

    def show_and_activate(self) -> bool:
        """Show activation dialog. Returns True if activation succeeded."""
        try:
            return self._run_dialog()
        except Exception:
            logger.exception("ActivationDialog failed")
            return False

    def _run_dialog(self) -> bool:
        from PyQt6.QtCore import Qt
        from PyQt6.QtWidgets import (
            QApplication,
            QDialog,
            QHBoxLayout,
            QLabel,
            QLineEdit,
            QMessageBox,
            QPushButton,
            QVBoxLayout,
        )

        app = QApplication.instance() or QApplication(sys.argv)

        while True:
            dialog = QDialog()
            dialog.setWindowTitle("MuraveyChina — Activation")
            dialog.setFixedSize(460, 280)
            dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)

            layout = QVBoxLayout(dialog)
            layout.setContentsMargins(24, 24, 24, 24)
            layout.setSpacing(16)

            # Header
            header = QLabel("<b>MuraveyChina — License Activation</b>")
            header.setStyleSheet("font-size: 16px;")
            layout.addWidget(header)

            # Info text
            info = QLabel(
                "A license is required to use MuraveyChina.\n\n"
                "Already purchased? Enter your activation token below.\n"
                "No token yet? Click «Buy» to open the purchase page."
            )
            info.setWordWrap(True)
            layout.addWidget(info)

            # Machine ID (copyable)
            from src.license.machine_fingerprint import get_machine_id
            mid = get_machine_id()
            mid_label = QLabel(f"Machine ID: <code>{mid}</code>")
            mid_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
            mid_label.setStyleSheet("font-size: 11px; color: #666; background: #f0f0f0; padding: 4px;")
            layout.addWidget(mid_label)

            # Token field
            token_field = QLineEdit()
            token_field.setPlaceholderText("Paste activation token…")
            token_field.setMinimumHeight(32)
            layout.addWidget(token_field)

            # Status label
            status_label = QLabel("")
            status_label.setStyleSheet("color: gray; font-size: 12px;")
            layout.addWidget(status_label)

            # Buttons
            btn_layout = QHBoxLayout()

            btn_buy = QPushButton("Buy")
            btn_buy.setMinimumHeight(36)
            btn_buy.clicked.connect(lambda: webbrowser.open(PURCHASE_PAGE_URL))
            btn_layout.addWidget(btn_buy)

            btn_layout.addStretch()

            btn_cancel = QPushButton("Exit")
            btn_cancel.setMinimumHeight(36)
            btn_cancel.clicked.connect(dialog.reject)
            btn_layout.addWidget(btn_cancel)

            btn_activate = QPushButton("Activate")
            btn_activate.setMinimumHeight(36)
            btn_activate.setDefault(True)
            btn_layout.addWidget(btn_activate)

            layout.addLayout(btn_layout)

            # Activation handler
            result_holder = [False]

            def on_activate():
                token = token_field.text().strip()
                if not token:
                    status_label.setText("Please enter your activation token")
                    status_label.setStyleSheet("color: red; font-size: 12px;")
                    return

                status_label.setText("Validating…")
                status_label.setStyleSheet("color: blue; font-size: 12px;")
                app.processEvents()

                activation = self._mgr.activate(token)

                if activation.success:
                    QMessageBox.information(
                        dialog,
                        "MuraveyChina",
                        "Activation successful! Your license is now active.",
                    )
                    result_holder[0] = True
                    dialog.accept()
                else:
                    # Make error messages human-readable
                    err = activation.error or "Unknown error"
                    if "expired" in err.lower():
                        err = "Token expired. Purchase a new one at whop.com/muravey-ai"
                    elif "machine" in err.lower() and "mismatch" in err.lower():
                        err = "This token belongs to another computer. Each token works on one machine only."
                    elif "invalid" in err.lower() or "signature" in err.lower():
                        err = "Invalid token. Check that you copied it correctly (no extra spaces)."
                    elif "revoked" in err.lower():
                        err = "This token has been revoked. Contact support."
                    elif "unreachable" in err.lower() or "connection" in err.lower():
                        err = "Cannot reach license server. Check your internet connection."
                    status_label.setText(err)
                    status_label.setStyleSheet("color: red; font-size: 12px;")

            btn_activate.clicked.connect(on_activate)
            token_field.returnPressed.connect(on_activate)

            # Center on screen
            if screen := app.primaryScreen():
                geo = screen.availableGeometry()
                dialog.move(
                    geo.center().x() - dialog.width() // 2,
                    geo.center().y() - dialog.height() // 2,
                )

            code = dialog.exec()
            if result_holder[0]:
                return True
            if code == QDialog.DialogCode.Rejected:
                return False

    def show_expiry_warning(self, minutes_remaining: int) -> None:
        """Show system notification when session is about to expire."""
        try:
            from PyQt6.QtWidgets import QApplication, QSystemTrayIcon

            app = QApplication.instance()
            if app:
                for widget in app.topLevelWidgets():
                    tray = widget.findChild(QSystemTrayIcon)
                    if tray:
                        tray.showMessage(
                            "MuraveyChina",
                            f"License expires in {minutes_remaining} minutes. Please renew.",
                            QSystemTrayIcon.MessageIcon.Warning,
                            5000,
                        )
                        return
        except Exception:
            pass
        logger.warning("Session expires in %d minutes", minutes_remaining)

    def show_expired_dialog(self) -> None:
        """Show dialog when session has expired."""
        try:
            from PyQt6.QtWidgets import QApplication, QMessageBox

            app = QApplication.instance() or QApplication(sys.argv)
            reply = QMessageBox.question(
                None,
                "MuraveyChina — License Expired",
                "Your license has expired.\n\nPurchase a new license to continue.",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            )
            if reply == QMessageBox.StandardButton.Yes:
                webbrowser.open(PURCHASE_PAGE_URL)
        except Exception:
            logger.exception("show_expired_dialog failed")
