from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from .about_xml import AboutModMetadata, load_about_xml
from .load_folders import LoadFolders, load_load_folders_xml


class ModFolderError(ValueError):
    """Raised when a mod folder does not contain the expected files."""


@dataclass(frozen=True)
class ModFolder:
    path: Path
    about: AboutModMetadata
    load_folders: LoadFolders | None = None


def load_mod_folder(path: Path) -> ModFolder:
    mod_path = path.resolve()
    if not mod_path.is_dir():
        raise ModFolderError(f"mod folder path is not a directory: {mod_path}")

    about_path = mod_path / "About" / "About.xml"
    if not about_path.is_file():
        raise ModFolderError(f"missing required file: {about_path}")

    load_folders_path = mod_path / "LoadFolders.xml"
    load_folders = (
        load_load_folders_xml(load_folders_path)
        if load_folders_path.is_file()
        else None
    )

    return ModFolder(
        path=mod_path,
        about=load_about_xml(about_path),
        load_folders=load_folders,
    )


def try_load_mod_folder(path: Path) -> ModFolder | None:
    try:
        return load_mod_folder(path)
    except Exception:
        return None
