from __future__ import annotations

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

from pathlib import Path
from tempfile import TemporaryDirectory
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from PySide6.QtWidgets import QApplication

from database import Database
from item_catalog import CatalogIdentity, VariantSelection
from models import Identity, InventoryItem
from official_stats import OfficialItemClient
from rules import RuleBook


def _rules() -> RuleBook:
    return RuleBook(Path(__file__).resolve().parents[1] / "data")


def test_official_stats_extracts_awakening_images():
    selection = VariantSelection(CatalogIdentity("amulet", "", "amulet", ""))
    html = """
    <html><body>
      <table class="itemImagesContainer">
        <tr><td><div class="itemMainImageContainer" style="background:url('gfx/items/main.jpg')"></div></td></tr>
        <tr><td class="itemAffixContainer"><a href="gfx/items/prefix.jpg">Image</a></td>
            <td class="itemAffixContainer"><img src="/gfx/items/suffix.jpg" alt="Image"></td></tr>
      </table>
      <div>Przedmiot: Amulet Amulet (PŁEĆ: M) Cena: 1 PLN Cena sprzedaży: 1 PLN
      Mana: 0 Nanity: 0 STREFA - Przedmiot: 1 STREFA - PODSUMOWANIE: 1
      Rzadkość - Przedmiot: 1 Rzadkość - PODSUMOWANIE: 1</div>
    </body></html>
    """
    stats = OfficialItemClient.parse(
        html, selection, "https://r21.bloodwars.pl/test_items.php/?baseType=6"
    )
    assert stats.main_image_url == "https://r21.bloodwars.pl/gfx/items/main.jpg"
    assert stats.prefix_image_url == "https://r21.bloodwars.pl/gfx/items/prefix.jpg"
    assert stats.suffix_image_url == "https://r21.bloodwars.pl/gfx/items/suffix.jpg"


def test_inventory_image_paths_roundtrip_in_database():
    with TemporaryDirectory() as td:
        db = Database(Path(td) / "planner.db")
        profile_id = db.upsert_profile("Tester", "R21PL", "Moria")
        item = InventoryItem(
            db_id=None,
            profile_id=None,
            import_id=None,
            item_id="123",
            full_name="Dobry Amulet",
            identity=Identity("amulet", "amulet"),
            quality="Dobry",
            upgrade=0,
            level=6,
            main_image="C:/cache/main.jpg",
            prefix_image="C:/cache/prefix.jpg",
            suffix_image="C:/cache/suffix.jpg",
        )
        db.import_inventory(profile_id, [item], {"source_file": "x.html", "source_hash": "x"})
        loaded = db.active_items(profile_id)[0]
        assert loaded.main_image.endswith("main.jpg")
        assert loaded.prefix_image.endswith("prefix.jpg")
        assert loaded.suffix_image.endswith("suffix.jpg")
        db.close()


def test_awakening_window_smoke(monkeypatch):
    import awakening_app
    from awakening_theme import apply_theme

    app = QApplication.instance() or QApplication([])
    apply_theme(app)
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        window = awakening_app.MainWindow()
        assert window.tabs.count() == 6
        assert window.enc_detail_panel is not None
        assert window.enc_visual.main.width() == 190
        window.close()
