import scanpy as sc
import mudata as mu
import sys

## VIASH START
par = {
    "input": "resources_test/pbmc_1k_protein_v3/pbmc_1k_protein_v3_filtered_feature_bc_matrix.h5mu",
    "output": "output.h5mu",
    "base": None,
    "modality": "rna",
    "output_layer": "foo",
}
meta = {"name": "lognorm"}
## VIASH END

sys.path.append(meta["resources_dir"])
from setup_logger import setup_logger
from compress_h5mu import write_h5ad_to_h5mu_with_compression

logger = setup_logger()

logger.info("Reading modality %s from input mudata", par["modality"])
data = mu.read_h5ad(par["input"], mod=par["modality"])
assert data.var_names.is_unique, "Expected var_names to be unique."

logger.info("Performing log transformation")
# Make our own copy with not a lot of data
# this avoid excessive memory usage
input_layer = data.layers[par["input_layer"]] if par["input_layer"] else data.X

transformed_matrix = sc.pp.log1p(
    input_layer,
    base=par["base"],
    copy=True,  # Avoid accidental overwrites
)

if par["output_layer"]:
    data.layers[par["output_layer"]] = transformed_matrix
else:
    data.X = transformed_matrix
data.uns["log1p"] = {"base": par["base"]}

logger.info("Writing to file %s", par["output"])
write_h5ad_to_h5mu_with_compression(
    par["output"], par["input"], par["modality"], data, par["output_compression"]
)
