"""Offline E9 package preflight; never creates workflows or executes package content."""

import hashlib
import io
import os
from pathlib import Path, PurePosixPath
import re
import stat
import tempfile
import xml.etree.ElementTree as ET
import zipfile

MAX_INPUT = 64 * 1024 * 1024
MAX_EXPANDED = 128 * 1024 * 1024
MAX_ENTRIES = 4096


class PackageError(ValueError):
    def __init__(self, code, message):
        super().__init__(message)
        self.code = code


def _xml_info(raw):
    # Expat does not accept GBK bytes directly. Decode the declared charset first.
    if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
        encoding = "utf-16"
    else:
        match = re.search(br"encoding\s*=\s*['\"]([^'\"]+)['\"]", raw[:256])
        encoding = match.group(1).decode("ascii") if match else "utf-8-sig"
    try:
        text = raw.decode(encoding)
        if re.search(r"<!\s*(?:DOCTYPE|ENTITY)\b", text, re.I):
            raise PackageError("xml_declarations_rejected", "XML DTD/entity declarations are not accepted.")
        root = ET.fromstring(text)
    except (LookupError, UnicodeError, ET.ParseError, ValueError) as exc:
        if isinstance(exc, PackageError):
            raise
        raise PackageError("xml_invalid", "XML cannot be decoded or parsed.") from exc
    elements = root.findall("ELEMENT")
    # Native exports also contain grouping ELEMENT nodes without a table name.
    if root.tag != "root" or not elements or not any(e.get("TABLENAME") for e in elements):
        raise PackageError("xml_schema_unrecognized", "Expected E9 root/ELEMENT nodes including table metadata.")
    return {"encoding": encoding, "elementCount": len(elements)}


def _read(path):
    with Path(path).open("rb") as stream:
        raw = stream.read(MAX_INPUT + 1)
    if len(raw) > MAX_INPUT:
        raise PackageError("input_too_large", "Package exceeds the input size limit.")
    return raw


def _inspect(raw):
    base = {"sha256": hashlib.sha256(raw).hexdigest(), "bytes": len(raw),
            "businessValidated": False, "requiresNativeParser": True}
    # Java ZipInputStream starts at byte zero; Python ZipFile also accepts SFX prefixes.
    if raw.startswith(b"PK\x03\x04"):
        xml_count = encrypted_count = expanded = 0
        names = set()
        try:
            with zipfile.ZipFile(io.BytesIO(raw), metadata_encoding="gbk") as archive:
                entries = archive.infolist()
                if len(entries) > MAX_ENTRIES:
                    raise PackageError("too_many_entries", "Archive contains too many entries.")
                for entry in entries:
                    name = entry.filename
                    normalized = PurePosixPath(name).as_posix().casefold()
                    if ("\\" in name or ":" in name or name.startswith("/")
                            or ".." in PurePosixPath(name).parts
                            or stat.S_ISLNK(entry.external_attr >> 16)):
                        raise PackageError("unsafe_archive_entry", "Archive contains an unsafe path or symlink.")
                    if normalized in names:
                        raise PackageError("duplicate_archive_entry", "Archive entry names are ambiguous.")
                    names.add(normalized)
                    if entry.is_dir():
                        continue
                    if entry.flag_bits & 1:
                        raise PackageError("zip_password_not_supported", "E9 XML encryption is separate from ZIP password encryption.")
                    if entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
                        raise PackageError("zip_compression_not_supported", "Java ZipInputStream does not support this compression method.")
                    expanded += entry.file_size
                    if expanded > MAX_EXPANDED:
                        raise PackageError("expanded_size_exceeded", "Archive exceeds the expanded size limit.")
                    # Reading verifies CRC before any output package is created.
                    body = archive.read(entry)
                    if name.lower().endswith(".xml"):
                        _xml_info(body)
                        xml_count += 1
                    elif name.lower().endswith(".exml"):
                        if not body:
                            raise PackageError("encrypted_xml_empty", "Encrypted XML entry is empty.")
                        encrypted_count += 1
                if not xml_count and not encrypted_count:
                    raise PackageError("workflow_xml_missing", "Archive has no XML/EXML; native getImportType can return an empty object.")
                return {**base, "status": "native_zip_candidate", "entryCount": len(entries),
                        "xmlCount": xml_count, "encryptedXmlCount": encrypted_count}
        except (zipfile.BadZipFile, EOFError, NotImplementedError, RuntimeError) as exc:
            raise PackageError("zip_invalid", "ZIP structure, compression, or CRC verification failed.") from exc
    stripped = raw.lstrip(b"\xef\xbb\xbf \r\n\t")
    if stripped.startswith(b"<") or raw.startswith((b"\xff\xfe", b"\xfe\xff")):
        return {**base, "status": "xml_packaging_available", **_xml_info(raw)}
    if zipfile.is_zipfile(io.BytesIO(raw)):
        raise PackageError("zip_prefix_not_supported", "Archive prefix is incompatible with Java ZipInputStream; it is not removed automatically.")
    raise PackageError("unrecognized_container", "Input is neither a native ZIP nor readable E9 XML. Encryption or damage is not determined; renaming cannot repair it.")


def inspect_package(path):
    return _inspect(_read(path))


def pack_xml(source, destination):
    """Wrap recognized XML without changing its bytes; never overwrite any existing file."""
    raw = _read(source)
    info = _inspect(raw)
    if info["status"] != "xml_packaging_available":
        raise PackageError("pack_requires_xml", "Packing accepts only readable E9 XML, not opaque or existing ZIP data.")
    destination = Path(destination)
    temporary = None
    try:
        with tempfile.NamedTemporaryFile(dir=destination.parent, prefix=".wewf-", delete=False) as stream:
            temporary = Path(stream.name)
            with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive:
                member = zipfile.ZipInfo("workflow.xml", (1980, 1, 1, 0, 0, 0))
                member.compress_type = zipfile.ZIP_DEFLATED
                archive.writestr(member, raw)
        output = inspect_package(temporary)
        os.link(temporary, destination)  # Exclusive publication: fails if destination exists.
        return {**output, "status": "xml_packaged", "sourceSha256": info["sha256"]}
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)


def validate_parser_response(response):
    """HTTP 200 alone is not native parser success."""
    if not isinstance(response, dict) or not response:
        raise PackageError("native_parser_empty", "Native parser returned no workflow metadata; do not invoke getImportInfo.")
    if not isinstance(response.get("importtype"), list) or not response["importtype"]:
        raise PackageError("native_parser_metadata_missing", "Native import type options are missing.")
    if str(response.get("importtypevalue")) not in {"0", "1"}:
        raise PackageError("native_parser_type_invalid", "Native parser did not return a recognized import type.")
    return {"status": "native_parser_metadata_present", "businessValidated": False,
            "requiresDependencyReview": True}
