import os
import zipfile
import tempfile


REQUIRED_FILES = {
    "parcels_o.gml",
    "parcels.gml",
    "buildings_o.gml",
    "buildings.gml",
    "elab.xml",
}


class CadastreZipPackage:
    def __init__(self, zip_path=None, extract_dir=None, files=None):
        self.zip_path = zip_path
        self.extract_dir = extract_dir
        self.files = files or {}

    def get_path(self, name):
        return self.files.get(name)


def load_cadastre_zip(zip_path):
    if not os.path.isfile(zip_path):
        raise FileNotFoundError(f"ZIP not found: {zip_path}")

    extract_dir = tempfile.mkdtemp(prefix="cadastre_zip_")

    with zipfile.ZipFile(zip_path, "r") as zf:
        zf.extractall(extract_dir)

    found_files = {}
    for root, dirs, files in os.walk(extract_dir):
        for fname in files:
            if fname in REQUIRED_FILES:
                found_files[fname] = os.path.join(root, fname)

    missing = REQUIRED_FILES - set(found_files.keys())
    if missing:
        raise ValueError(
            "Invalid cadastre ZIP structure. Missing files: "
            + ", ".join(sorted(missing))
        )

    return CadastreZipPackage(zip_path, extract_dir, found_files)


def build_package_from_session_files(files, extract_dir=None):
    missing = REQUIRED_FILES - set(files.keys())
    if missing:
        raise ValueError(
            "Session source files incomplete. Missing: "
            + ", ".join(sorted(missing))
        )

    return CadastreZipPackage(
        zip_path=None,
        extract_dir=extract_dir,
        files=files
    )