# [CRUCIBLE-SEED]
# category: path_traversal
# severity: high
# language: python
# expected: path traversal via zipfile extraction without entry path validation (zip-slip)

import os
import zipfile


EXTRACT_BASE = "/var/app/uploads/extracted"


def extract_archive(zip_bytes: bytes, user_id: str) -> list:
    import io
    extracted = []
    with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
        for entry in zf.infolist():
            # entry.filename can contain "../" — writes outside EXTRACT_BASE
            output_path = os.path.join(EXTRACT_BASE, user_id, entry.filename)
            if entry.is_dir():
                os.makedirs(output_path, exist_ok=True)
            else:
                os.makedirs(os.path.dirname(output_path), exist_ok=True)
                with zf.open(entry) as src, open(output_path, "wb") as dst:
                    dst.write(src.read())
                extracted.append(output_path)
    return extracted


def get_extracted_file(user_id: str, relative_path: str) -> bytes:
    full_path = os.path.join(EXTRACT_BASE, user_id, relative_path)
    with open(full_path, "rb") as f:
        return f.read()
