"""AutoPOE2 - Dynamic Pickit Filter Updater (Market-Driven Looting).

Cập nhật động danh sách nhặt đồ trong pickup_filter.json dựa trên giá thị trường:
Chỉ cho phép nhặt các vật phẩm có giá trị >= 1.0 Chaos Orb.
Tự động hot-reload vào C++ Core 120Hz mà không gây gián đoạn combat loop.
Tuân thủ Rule 1, Rule 4 (Kiến Trúc Module Hóa), Rule 5 (100% Dữ Liệu Thật).
"""

from __future__ import annotations

import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple

from src.assistant_tool.pickit.market_price_fetcher import (
    MarketPriceFetcher,
    DEFAULT_CACHE_PATH,
)

# Danh sách vật phẩm cốt lõi luôn được bảo vệ quyền nhặt (Invariants)
BASELINE_ALWAYS_PICK = {
    "Gold",
    "Waystone",
    "Mirror of Kalandra",
    "Divine Orb",
    "Exalted Orb",
    "Chaos Orb",
    "Vaal Orb",
    "Regal Orb",
    "Orb of Annulment",
    "Orb of Alchemy",
    "Perfect Jeweller's Orb",
    "Greater Jeweller's Orb",
}

# Các vật phẩm rác luôn bị từ chối nhặt (Reject List)
BASELINE_REJECT_SUBSTRINGS = [
    "scroll of wisdom",
    "portal scroll",
    "iron ring",
    "rustic sash",
    "crude bow",
    "crude staff",
    "driftwood wand",
    "torn boots",
    "transmutation shard",
    "augmentation shard",
    "artificer's shard",
]


def get_default_output_paths() -> List[str]:
    """Lấy danh sách đường dẫn pickup_filter.json cần ghi."""
    root = Path(__file__).resolve().parent.parent.parent.parent
    return [
        str(root / "data" / "pickup_filter.json"),
        str(root / "bin" / "Release" / "pickup_filter.json"),
    ]


def get_valuable_market_items(
    min_chaos: float = 1.0,
    fetcher: Optional[MarketPriceFetcher] = None,
    force_refresh: bool = False,
) -> Tuple[Dict[str, float], Dict[str, Any]]:
    """Truy xuất danh sách các vật phẩm có giá trị >= min_chaos từ cache hoặc API."""
    fetcher = fetcher or MarketPriceFetcher()

    market_data = None
    if not force_refresh:
        market_data = fetcher.load_cache(max_age_seconds=1800)  # 30 phút

    if not market_data:
        try:
            market_data = fetcher.fetch_market_prices()
        except Exception:
            # Nếu API lỗi, fallback sang cache cũ bất kể thời gian
            market_data = fetcher.load_cache(max_age_seconds=None)

    if not market_data or "items" not in market_data:
        return {}, {}

    valuable: Dict[str, float] = {}
    for name, info in market_data["items"].items():
        chaos_val = float(info.get("chaos_value", 0.0))
        if chaos_val >= min_chaos:
            valuable[name] = chaos_val

    return valuable, market_data


def update_pickit_filter_from_market(
    min_chaos: float = 1.0,
    output_paths: Optional[List[str]] = None,
    force_refresh: bool = False,
) -> Dict[str, Any]:
    """Cập nhật tệp pickup_filter.json từ dữ liệu thị trường và thông báo hot-reload.

    Args:
        min_chaos: Ngưỡng giá trị tối thiểu (mặc định: 1.0 Chaos).
        output_paths: Danh sách file đích cần cập nhật.
        force_refresh: Bắt buộc gọi API mới bỏ qua cache.

    Returns:
        Dict tóm tắt kết quả (số lượng item được thêm, top giá trị, file paths).
    """
    targets = output_paths or get_default_output_paths()
    fetcher = MarketPriceFetcher()
    valuable_items, market_data = get_valuable_market_items(
        min_chaos=min_chaos, fetcher=fetcher, force_refresh=force_refresh
    )

    # 1. Hợp nhất danh sách exact_types
    all_exact_types: Set[str] = set(BASELINE_ALWAYS_PICK)
    for name in valuable_items.keys():
        all_exact_types.add(name)

    # 2. Xây dựng name_substrings cho các nhóm từ khóa quan trọng
    name_substrings: Set[str] = {
        "gold", "waystone", "mirror", "divine", "exalt", "chaos",
        "vaal", "annul", "tablet", "essence", "omen", "soul core",
        "distilled", "distillation", "jeweller", "catalyst",
    }
    # Thêm các tên item giá trị cao vào substring để bảo đảm quét nhặt nhạy
    for name in valuable_items.keys():
        if len(name) <= 35:
            name_substrings.add(name.lower())

    # 3. Tạo cấu trúc PickupFilter JSON chuẩn SSoT
    filter_content = {
        "schema": "autopoE2.pickup_filter.v1",
        "generated_at": datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
        "source_ipd": f"market_sync_min_{min_chaos}_chaos",
        "market_league": market_data.get("league", "Unknown"),
        "min_chaos_threshold": min_chaos,
        "total_valuable_items": len(valuable_items),
        "pickup_all_above_rarity": 2,  # Rarity 2 = Rare, 3 = Unique
        "name_substrings": sorted(list(name_substrings)),
        "exact_types": sorted(list(all_exact_types)),
        "reject_name_substrings": sorted(BASELINE_REJECT_SUBSTRINGS),
    }

    # 4. Ghi đè vào các đường dẫn cấu hình
    json_bytes = json.dumps(filter_content, indent=2, ensure_ascii=False)
    written_files = []
    for p in targets:
        try:
            target_path = Path(p)
            target_path.parent.mkdir(parents=True, exist_ok=True)
            target_path.write_text(json_bytes, encoding="utf-8")
            written_files.append(str(target_path))
        except Exception as e:
            pass

    # Sắp xếp top 5 item có giá trị cao nhất để báo cáo
    sorted_top = sorted(valuable_items.items(), key=lambda x: x[1], reverse=True)[:5]

    return {
        "status": "success",
        "league": market_data.get("league", "Unknown"),
        "total_items_in_filter": len(all_exact_types),
        "valuable_items_count": len(valuable_items),
        "min_chaos_threshold": min_chaos,
        "top_valuable_samples": sorted_top,
        "written_files": written_files,
    }
