"""macOS settings window using Cocoa/PyObjC.

Simple tabbed preferences window with AI, hotkey, update, and about tabs.
"""

from __future__ import annotations

import logging
from collections.abc import Callable

from ..config import Config
from ..i18n import _

log = logging.getLogger(__name__)


class SettingsWindow:
    """macOS settings window via Cocoa NSWindow."""

    def __init__(
        self,
        config: Config,
        on_hotkey_change: Callable[[str], bool] | None = None,
        on_check_update: Callable[[], None] | None = None,
        on_clear_cache: Callable[[], int] | None = None,
        on_language_change: Callable[[str], None] | None = None,
        on_theme_change: Callable[[str], None] | None = None,
        on_prompts_hotkey_change: Callable[[str], bool] | None = None,
        on_vision_hotkey_change: Callable[[str], bool] | None = None,
    ) -> None:
        self._config = config
        self._on_hotkey_change = on_hotkey_change
        self._on_check_update = on_check_update
        self._on_clear_cache = on_clear_cache
        self._on_language_change = on_language_change
        self._on_theme_change = on_theme_change
        self._on_prompts_hotkey_change = on_prompts_hotkey_change
        self._on_vision_hotkey_change = on_vision_hotkey_change
        self._window = None

    def show(self) -> None:
        """Show the settings window."""
        try:
            self._show_cocoa()
        except ImportError:
            log.warning("PyObjC not available — showing terminal-based settings")
            self._show_terminal()
        except Exception as exc:
            log.error("Failed to show settings: %s", exc)

    def _show_cocoa(self) -> None:
        """Build and show an NSWindow with NSTabView."""
        import AppKit  # type: ignore[import]

        from src import __version__

        # Create window
        win = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            AppKit.NSMakeRect(200, 300, 520, 420),
            (
                AppKit.NSTitledWindowMask
                | AppKit.NSClosableWindowMask
                | AppKit.NSMiniaturizableWindowMask
            ),
            AppKit.NSBackingStoreBuffered,
            False,
        )
        win.setTitle_(f"MuraveyChina v{__version__} — {_('settings.title')}")
        win.center()

        content = win.contentView()

        # Tab view
        tab_view = AppKit.NSTabView.alloc().initWithFrame_(AppKit.NSMakeRect(10, 50, 500, 360))
        tab_view.setAutoresizingMask_(AppKit.NSViewWidthSizable | AppKit.NSViewHeightSizable)

        # AI tab
        ai_item = AppKit.NSTabViewItem.alloc().initWithIdentifier_("ai")
        ai_item.setLabel_(_("settings.tab_ai"))
        ollama_note = (
            (
                f"\n{_('settings.ai.ollama_group')}: {self._config.ollama_base_url}"
                "\nhttps://ollama.com → ollama pull llama3.2"
            )
            if self._config.provider == "ollama"
            else ""
        )
        provider_label = AppKit.NSTextField.labelWithString_(
            f"{_('settings.ai.provider')} {self._config.provider}\n"
            f"{_('settings.ai.model')} {self._config.model}\n"
            f"Ollama URL: {self._config.ollama_base_url}"
            f"{ollama_note}\n\n"
            'python3 -c "from src.security.privacy_manager import save_api_key; '
            "save_api_key('deepseek', 'sk-YOUR-KEY')\""
        )
        provider_label.setFrame_(AppKit.NSMakeRect(10, 10, 470, 140))
        provider_label.setLineBreakMode_(AppKit.NSLineBreakByWordWrapping)
        ai_view = AppKit.NSView.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 500, 320))
        ai_view.addSubview_(provider_label)
        ai_item.setView_(ai_view)
        tab_view.addTabViewItem_(ai_item)

        # Hotkey tab
        hk_item = AppKit.NSTabViewItem.alloc().initWithIdentifier_("hotkey")
        hk_item.setLabel_(_("settings.tab_hotkey"))
        hk_label = AppKit.NSTextField.labelWithString_(
            f"{_('settings.hotkey.current_active', hotkey=self._config.hotkey)}\n\n"
            "~/Library/Application Support/MuraveyChina/config.yaml\n\n"
            "cmd+shift+space"
        )
        hk_label.setFrame_(AppKit.NSMakeRect(10, 10, 470, 120))
        hk_label.setLineBreakMode_(AppKit.NSLineBreakByWordWrapping)
        hk_view = AppKit.NSView.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 500, 320))
        hk_view.addSubview_(hk_label)
        hk_item.setView_(hk_view)
        tab_view.addTabViewItem_(hk_item)

        content.addSubview_(tab_view)

        # OK button
        ok_btn = AppKit.NSButton.alloc().initWithFrame_(AppKit.NSMakeRect(420, 10, 80, 32))
        ok_btn.setTitle_("OK")
        ok_btn.setBezelStyle_(AppKit.NSBezelStyleRounded)
        ok_btn.setTarget_(win)
        ok_btn.setAction_("close")
        content.addSubview_(ok_btn)

        win.makeKeyAndOrderFront_(None)
        self._window = win

    def _show_terminal(self) -> None:
        """Fallback: log settings info when Cocoa is unavailable."""
        from src import __version__

        log.info("=== MuraveyChina v%s %s ===", __version__, _("settings.title"))
        log.info("%s %s", _("settings.ai.provider"), self._config.provider)
        log.info("%s %s", _("settings.ai.model"), self._config.model)
        log.info("%s: %s", _("settings.tab_hotkey"), self._config.hotkey)
        log.info("Auto-paste: %s", self._config.auto_paste)
        log.info("Ollama URL: %s", self._config.ollama_base_url)
