from __future__ import annotations

import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")

from pathlib import Path
from tempfile import TemporaryDirectory

from PySide6.QtWidgets import QApplication, QLabel, QMessageBox

from awakening_widgets import CheckableComboBox, ItemCardOverlay
from display_filters import item_matches
from image_repository import ImageRepository
from models import Identity, InventoryItem
from rules import RuleBook

ROOT = Path(__file__).resolve().parents[1]
RULES = RuleBook(ROOT / "data")


def _app() -> QApplication:
    return QApplication.instance() or QApplication([])


def test_checkable_combo_supports_multiple_values():
    _app()
    combo = CheckableComboBox()
    combo.set_values(["Pierścień", "Sygnet", "Bransoleta"])
    assert combo.selected_values() == []
    combo.set_selected_values(["Pierścień", "Sygnet"])
    assert set(combo.selected_values()) == {"Pierścień", "Sygnet"}
    assert combo.lineEdit().text() == "Pierścień, Sygnet"


def test_inventory_filter_accepts_multiple_prefixes_and_bases():
    item = InventoryItem(
        db_id=None,
        profile_id=None,
        import_id=None,
        item_id="1",
        full_name="Dobry Niedźwiedzi Sygnet Geniuszu",
        identity=Identity("rings", "sygnet", "niedzwiedzi", "geniuszu", False),
        quality="Dobry",
        upgrade=0,
        level=6,
    )
    assert item_matches(
        item,
        RULES,
        category=["Pierścień"],
        prefix=["Niedźwiedzi", "Pajęczy"],
        base=["Pierścień", "Sygnet"],
        suffix=["Geniuszu"],
    )
    assert not item_matches(item, RULES, base=["Pierścień", "Bransoleta"])


def test_planner_can_select_two_target_bases(monkeypatch):
    import awakening_app

    app = _app()
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        window = awakening_app.MainWindow()
        window.target_category.set_selected_values(["Pierścień"])
        window.refresh_target_options()
        window.target_prefix.set_selected_values(["Niedźwiedzi"])
        window.target_base.set_selected_values(["Pierścień", "Sygnet"])
        window.target_suffix.set_selected_values(["Geniuszu"])
        targets, _minimum = window.selected_targets()
        names = {window.rules.identity_display(target) for target in targets}
        assert names == {"Niedźwiedzi Pierścień Geniuszu", "Niedźwiedzi Sygnet Geniuszu"}
        window.close()
        app.processEvents()


def test_item_card_keeps_affix_icons_when_stats_fetch_has_only_main_image():
    app = _app()
    with TemporaryDirectory() as td:
        repo = ImageRepository(Path(td))
        overlay = ItemCardOverlay(repo)
        prefix_path = ROOT / "assets" / "prefEmpty.jpg"
        suffix_path = ROOT / "assets" / "sufEmpty.jpg"
        overlay.show_item(
            token="abc",
            title="Test",
            details=[("Poziom", "Dobry")],
            prefix_image=str(prefix_path),
            suffix_image=str(suffix_path),
            category="rings",
            base="Pierścień",
            prefix_name="Pajęczy",
            suffix_name="Geniuszu",
            base_key="pierscien",
            prefix_key="pajeczy",
            suffix_key="geniuszu",
        )
        before_prefix = overlay.visual._paths["prefix"]
        before_suffix = overlay.visual._paths["suffix"]
        overlay.update_official("abc", {"item_category": "Pierścień"}, main=str(prefix_path))
        assert overlay.visual._paths["prefix"] == before_prefix
        assert overlay.visual._paths["suffix"] == before_suffix
        overlay.close()
        app.processEvents()


def test_title_hint_and_fetch_button_reset(monkeypatch):
    import awakening_app

    app = _app()
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        monkeypatch.setattr(QMessageBox, "critical", lambda *args, **kwargs: QMessageBox.Ok)
        window = awakening_app.MainWindow()
        assert window.windowTitle() == "BW Crafting Tool by Arg"
        assert not any(
            isinstance(widget, QLabel) and "Kliknij przedmiot" in widget.text()
            for widget in window.findChildren(QLabel)
        )
        window.set_fetch_running(True)
        assert not window.enc_fetch_button.isEnabled()
        window.encyclopedia_fetch_failed(RuntimeError("test"))
        assert window.enc_fetch_button.isEnabled()
        window.close()
        app.processEvents()


def test_official_fetch_gate_does_not_queue(monkeypatch):
    import awakening_app

    app = _app()
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        window = awakening_app.MainWindow()
        assert window._begin_official_fetch("first", "key-1") is True
        assert window.fetch_running is True
        assert window._begin_official_fetch("second", "key-2") is False
        assert window._official_fetch_cache_key == "key-1"
        window._finish_official_fetch()
        assert window.fetch_running is False
        assert window._begin_official_fetch("third", "key-3") is True
        window._finish_official_fetch()
        window.close()
        app.processEvents()


def test_inventory_bulk_prefetch_is_disabled(monkeypatch):
    import awakening_app

    app = _app()
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        window = awakening_app.MainWindow()
        window.start_inventory_asset_prefetch([])
        assert window._image_prefetch_running is False
        assert not hasattr(window, "enc_batch_button")
        window.close()
        app.processEvents()
