"""Locate Content.ggpk, HashCache.dat, and an optional Oodle DLL. Never writes into the game install."""
from __future__ import annotations

import os
from pathlib import Path

DEFAULT_GGPK_PATH = Path(r"C:\Program Files (x86)\Grinding Gear Games\Path of Exile 2\Content.ggpk")

_GGPK_CANDIDATES = (
    DEFAULT_GGPK_PATH,
    Path(r"C:\Program Files\Grinding Gear Games\Path of Exile 2\Content.ggpk"),
    Path(r"C:\Program Files (x86)\Steam\steamapps\common\Path of Exile 2\Content.ggpk"),
    Path(r"D:\SteamLibrary\steamapps\common\Path of Exile 2\Content.ggpk"),
    Path(r"E:\SteamLibrary\steamapps\common\Path of Exile 2\Content.ggpk"),
)

_OODLE_NAMES = (
    "libooz.dll",
    "oozlib.dll",
    "oo2core.dll",
    "oo2core_9_win64.dll",
    "oo2core_8_win64.dll",
    "oo2core_7_win64.dll",
)


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[3]


def find_content_ggpk(explicit: str | Path | None = None) -> Path | None:
    if explicit:
        p = Path(explicit)
        return p if p.is_file() else None
    env = os.environ.get("AUTOPOE2_GGPK", "").strip()
    if env:
        p = Path(env)
        if p.is_file():
            return p
    for cand in _GGPK_CANDIDATES:
        if cand.is_file():
            return cand
    return None


def find_hashcache(ggpk: Path | None = None) -> Path | None:
    if ggpk is not None:
        p = ggpk.parent / "HashCache.dat"
        if p.is_file():
            return p
    found = find_content_ggpk()
    if found:
        p = found.parent / "HashCache.dat"
        if p.is_file():
            return p
    return None


def find_oodle_dll(explicit: str | Path | None = None) -> Path | None:
    if explicit:
        p = Path(explicit)
        return p if p.is_file() else None
    env = os.environ.get("AUTOPOE2_OODLE_DLL", "").strip()
    if env:
        p = Path(env)
        if p.is_file():
            return p
    search_dirs: list[Path] = [_repo_root() / "tools" / "bin"]
    ggpk = find_content_ggpk()
    if ggpk:
        search_dirs.append(ggpk.parent)
        search_dirs.append(ggpk.parent.parent / "Path of Exile")
    search_dirs.extend(
        [
            Path(r"C:\Program Files (x86)\Grinding Gear Games\Path of Exile"),
            Path(r"C:\Program Files (x86)\Steam\steamapps\common\Path of Exile"),
        ]
    )
    for folder in search_dirs:
        if not folder.is_dir():
            continue
        for name in _OODLE_NAMES:
            cand = folder / name
            if cand.is_file():
                return cand
        for cand in folder.glob("oo2core*.dll"):
            return cand
    return None
