#!/usr/bin/env python3
"""Verifica uma exportacao Lyntev JSONL e reconstitui dados/anexos localmente.

Python 3.10+, apenas biblioteca padrao. Nunca contacta a rede, executa conteudo
do ficheiro, usa nomes originais como caminhos ou substitui uma pasta existente.
"""
from pathlib import Path, PurePosixPath
import argparse, base64, binascii, collections, hashlib, json, os, re, shutil, tempfile, uuid

FORMAT = "lyntev-export-jsonl-v1"
MAX_LINE = 32 * 1024 * 1024
MAX_FILE = 16 * 1024 * 1024

class ExportError(ValueError):
    pass

def require(condition, message):
    if not condition:
        raise ExportError(message)

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        require(key not in result, "A exportacao contem uma chave JSON repetida.")
        result[key] = value
    return result

def natural(value):
    return isinstance(value, int) and not isinstance(value, bool) and value >= 0

def dump(path, value):
    with path.open("x", encoding="utf-8", newline="\n") as output:
        json.dump(value, output, ensure_ascii=False, indent=2, allow_nan=False)
        output.write("\n")

def verify_and_reconstruct(source, destination, expected_tenant=None):
    source = Path(source).resolve(strict=True)
    destination = Path(destination).absolute()
    parent = destination.parent.resolve(strict=True)
    require(parent.is_dir() and not destination.exists() and not destination.is_symlink(),
            "Escolha uma pasta de destino nova; nada sera substituido.")
    require(source.is_file(), "O ficheiro de origem nao existe.")
    stage = Path(tempfile.mkdtemp(prefix="." + destination.name + ".parcial-", dir=parent))
    require(stage.resolve().parent == parent and not stage.is_symlink(), "Destino temporario invalido.")
    chain = bytes(32)
    manifest = None
    counts = collections.Counter()
    seen_records, seen_files = set(), set()
    current = None
    complete = None
    file_index = []
    handles = {}
    total_bytes = 0
    try:
        (stage / "dados").mkdir()
        (stage / "anexos").mkdir()
        with source.open("rb") as stream:
            line_number = 0
            while True:
                raw = stream.readline(MAX_LINE + 1)
                if not raw:
                    break
                line_number += 1
                require(len(raw) <= MAX_LINE and raw.endswith(b"\n"), "Linha incompleta ou demasiado extensa.")
                require(complete is None, "Existem dados depois da conclusao.")
                try:
                    item = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
                                      parse_constant=lambda _: (_ for _ in ()).throw(ExportError("Numero JSON invalido.")))
                except (UnicodeError, json.JSONDecodeError) as error:
                    raise ExportError("JSON UTF-8 invalido na linha " + str(line_number) + ".") from error
                require(isinstance(item, dict), "Registo JSON invalido.")
                kind = item.get("type")
                if manifest is None:
                    require(kind == "manifest" and item.get("format") == FORMAT and isinstance(item.get("manifest"), dict),
                            "O ficheiro nao e uma exportacao Lyntev suportada.")
                    manifest = item["manifest"]
                    tenant = manifest.get("tenant")
                    try:
                        require(str(uuid.UUID(tenant)) == tenant.lower(), "Estabelecimento invalido.")
                    except (ValueError, TypeError, AttributeError) as error:
                        raise ExportError("Estabelecimento invalido.") from error
                    require(expected_tenant is None or tenant == expected_tenant, "A exportacao e de outro estabelecimento.")
                    require(manifest.get("version") == 1 and isinstance(manifest.get("datasets"), list)
                            and isinstance(manifest.get("storageBuckets"), list), "Manifesto invalido.")
                    datasets = [dataset.get("id") for dataset in manifest["datasets"] if isinstance(dataset, dict)]
                    require(all(isinstance(name, str) and re.fullmatch(r"[a-z][a-z0-9_]{0,80}", name) for name in datasets)
                            and len(datasets) == len(manifest["datasets"]) == len(set(datasets)),
                            "Conjuntos de dados invalidos.")
                    require("lyntev-build-assets" not in manifest["storageBuckets"], "O ficheiro inclui um ambito reservado.")
                    counts.update({name: 0 for name in datasets})
                    dump(stage / "manifesto.json", manifest)
                elif kind == "record":
                    dataset, key, data = item.get("dataset"), item.get("key"), item.get("data")
                    require(current is None and dataset in counts and isinstance(key, list) and isinstance(data, dict),
                            "Registo de dados invalido.")
                    identity = (dataset, json.dumps(key, sort_keys=True, separators=(",", ":"), allow_nan=False))
                    require(identity not in seen_records, "Existem registos repetidos.")
                    seen_records.add(identity)
                    if dataset not in handles:
                        handles[dataset] = (stage / "dados" / (dataset + ".jsonl")).open("x", encoding="utf-8", newline="\n")
                    handles[dataset].write(json.dumps(data, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n")
                    counts[dataset] += 1
                elif kind == "file-start":
                    identity, bucket, name, size = item.get("id"), item.get("bucket"), item.get("name"), item.get("bytes")
                    require(current is None and isinstance(identity, str) and re.fullmatch(r"[a-f0-9-]{36}", identity, re.I)
                            and str(uuid.UUID(identity)) == identity.lower() and identity not in seen_files,
                            "Identificador de anexo invalido ou repetido.")
                    require(bucket in manifest["storageBuckets"] and bucket != "lyntev-build-assets"
                            and isinstance(name, str) and 0 < len(name) <= 2048 and not name.startswith("/")
                            and "\\" not in name and "\0" not in name
                            and all(part not in ("", ".", "..") for part in name.split("/")),
                            "Nome ou ambito de anexo invalido.")
                    require(natural(size) and size <= MAX_FILE, "Tamanho de anexo invalido.")
                    suffix = PurePosixPath(name).suffix.lower()
                    if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix):
                        suffix = ".bin"
                    relative = "anexos/" + identity + suffix
                    handle = (stage / relative).open("xb")
                    current = {"id": identity, "bucket": bucket, "name": name, "mime": item.get("mime"),
                               "bytes": size, "offset": 0, "path": relative, "handle": handle, "hash": hashlib.sha256()}
                    seen_files.add(identity)
                elif kind == "file-chunk":
                    require(current is not None and item.get("id") == current["id"]
                            and natural(item.get("offset")) and item.get("offset") == current["offset"] and isinstance(item.get("base64"), str),
                            "A ordem dos anexos esta incompleta.")
                    try:
                        content = base64.b64decode(item["base64"], validate=True)
                    except (ValueError, binascii.Error) as error:
                        raise ExportError("Conteudo de anexo invalido.") from error
                    require(len(content) <= 65536 and current["offset"] + len(content) <= current["bytes"],
                            "O tamanho do anexo nao corresponde ao declarado.")
                    current["handle"].write(content)
                    current["hash"].update(content)
                    current["offset"] += len(content)
                elif kind == "file-end":
                    require(current is not None and item.get("id") == current["id"]
                            and item.get("bytes") == current["bytes"] == current["offset"], "Anexo incompleto.")
                    current["handle"].close()
                    file_index.append({key: current[key] for key in ("id", "bucket", "name", "mime", "bytes", "path")}
                                      | {"sha256": current["hash"].hexdigest()})
                    total_bytes += current["bytes"]
                    current = None
                elif kind == "complete":
                    require(current is None and item.get("format") == FORMAT and item.get("tenant") == manifest["tenant"]
                            and item.get("chainSha256") == chain.hex() and item.get("counts") == dict(counts)
                            and isinstance(item.get("counts"), dict) and all(natural(value) for value in item["counts"].values())
                            and natural(item.get("files")) and natural(item.get("fileBytes"))
                            and item.get("files") == len(file_index) and item.get("fileBytes") == total_bytes,
                            "A integridade ou as contagens da exportacao nao foram confirmadas.")
                    complete = item
                elif kind == "error":
                    raise ExportError("A exportacao foi interrompida pelo servidor; obtenha uma nova copia.")
                else:
                    raise ExportError("Tipo de registo desconhecido.")
                if kind != "complete":
                    chain = hashlib.sha256(chain + raw).digest()
        require(manifest is not None and complete is not None and current is None, "Exportacao incompleta.")
        for handle in handles.values():
            handle.close()
        for dataset, count in counts.items():
            if count == 0:
                (stage / "dados" / (dataset + ".jsonl")).touch(exist_ok=False)
        dump(stage / "indice-anexos.json", file_index)
        dump(stage / "VERIFICADO.json", complete)
        require(not destination.exists() and not destination.is_symlink(), "A pasta de destino ja existe.")
        os.rename(stage, destination)
        return {"datasets": len(counts), "records": sum(counts.values()), "files": len(file_index), "fileBytes": total_bytes}
    finally:
        if current is not None:
            current["handle"].close()
        for handle in handles.values():
            handle.close()
        # Only remove the exact temporary directory created by this invocation.
        if stage.exists():
            require(stage.resolve().parent == parent and stage.name.startswith("." + destination.name + ".parcial-")
                    and not stage.is_symlink(), "Limpeza do destino temporario recusada.")
            shutil.rmtree(stage)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("ficheiro", type=Path)
    parser.add_argument("pasta_nova", type=Path)
    parser.add_argument("--tenant", help="Identificador esperado do estabelecimento, opcional.")
    arguments = parser.parse_args()
    try:
        result = verify_and_reconstruct(arguments.ficheiro, arguments.pasta_nova, arguments.tenant)
    except (ExportError, OSError, ValueError) as error:
        parser.exit(1, "Nao foi criada uma copia verificada: " + str(error) + "\n")
    print("Exportacao verificada e reconstituida: " + json.dumps(result, ensure_ascii=False))

if __name__ == "__main__":
    main()
