from __future__ import annotations

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

from pathlib import Path
from tempfile import TemporaryDirectory
import time

from PySide6.QtWidgets import QApplication

from inventory_parser import parse_armory_html
from models import Identity
from planner import Planner
from rules import RuleBook

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


def test_pajeczy_ring_shortest_plans_stream_live_without_duplicate_missing_items():
    html_path = Path("/mnt/data/22.06.html")
    if not html_path.exists():
        return
    items, _meta = parse_armory_html(html_path, RULES)
    target = Identity("rings", "pierscien", "pajeczy", "", False)
    events: list[dict] = []
    planner = Planner(RULES)
    started = time.monotonic()
    plans = planner.find_plans(
        target,
        items,
        max_depth=5,
        top_k=25,
        timeout_seconds=30,
        allow_missing=True,
        progress_callback=events.append,
    )
    elapsed = time.monotonic() - started
    assert plans
    assert elapsed < 10
    assert all(plan.step_count == plans[0].step_count for plan in plans)
    assert all(len({item.key() for item in plan.missing}) == len(plan.missing) for plan in plans)
    kinds = [event.get("kind") for event in events]
    assert "plan" in kinds
    assert kinds.index("plan") < kinds.index("complete")


def test_timeout_ui_is_entered_in_minutes(monkeypatch):
    import awakening_app

    app = QApplication.instance() or QApplication([])
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        window = awakening_app.MainWindow()
        window.target_timeout.setCurrentText("2.5")
        assert window.planner_timeout_value() == 150.0
        window.target_timeout.setCurrentText("Bez limitu")
        assert window.planner_timeout_value() is None
        window.close()
        app.processEvents()


def test_live_plan_event_populates_right_hand_plan_table(monkeypatch):
    import awakening_app
    from models import CraftStep, Plan

    app = QApplication.instance() or QApplication([])
    with TemporaryDirectory() as td:
        monkeypatch.setattr(awakening_app, "app_storage_dir", lambda: Path(td))
        window = awakening_app.MainWindow()
        target = Identity("rings", "pierscien", "pajeczy", "", False)
        left = Identity("rings", "sygnet", "czarny", "", False)
        right = Identity("rings", "bransoleta", "spaczony", "", False)
        plan = Plan(
            target=target,
            steps=[CraftStep(left, right, target, "missing", "missing", 1)],
            consumed_item_ids=[],
            missing=[left, right],
            result_level=1,
            notes=[],
        )
        window.handle_planner_event({"kind": "plan", "plan": plan, "elapsed": 0.1, "message": "test"})
        assert window.plan_table.rowCount() == 1
        assert window.current_plans[0].step_count == 1
        window.close()
        app.processEvents()
