"""This is assemble_recipe, that is used by Assembler object as a source of
specific 'assemble_kernel' and other auxiliary procedures and settings in
the course of performing assembling of a stack into a tensor.
Members marked as 'MANDATORY' are required to be defined in this file.
Values of the members marked as 'OVERRIDDEN' are updated by the assembling call
by OCLI. Their values may be specified in this file for illustrative or testing purposes."""
#  NOTICE: Confidential and Proprietary Information of OPT/NET B.V.
#
#  This file contains confidential and proprietary information of OPT/NET B.V. and is intended solely for use by authorized personnel.
#  Unauthorized disclosure, reproduction, distribution, or use of this file, in whole or in part, without the express written permission of OPT/NET B.V., is strictly prohibited. This includes, but is not limited to, sharing this file or its contents with third parties or uploading it to public repositories or forums.
#
#  Developers are reminded to exercise caution and maintain the confidentiality of proprietary information when working with this file.
#  Any unauthorized sharing or distribution of this file may result in disciplinary action, including termination of employment, and may expose OPT/NET B.V. to legal liabilities.
#
#  For questions or clarifications regarding the handling of confidential information, developers should contact the Information Security Officer or the appropriate authority within OPT/NET B.V. before sharing or disclosing this file to third parties.
#
#  By using this file, developers acknowledge and agree to abide by the confidentiality and proprietary rights policies of OPT/NET B.V.
#
#  Copyright © 2026 OPT/NET B.V. All rights reserved.

import numpy as np

from ocli.ai.filter import Filter
from ocli.core.exception import ocli_assert

# MANDATORY, OVERRIDDEN: Source (stack) folder path
DATADIR = ""
# MANDATORY, OVERRIDDEN: Output (tensor) folder path
TNSRDIR = ""

# MANDATORY: Input stack layers (Landsat-8 Collection 2 Level-2 SR bands B1-B7)
input_list = [
    {"fname": "master_band_1", "type": "intensity", "band": "B1"},
    {"fname": "master_band_2", "type": "intensity", "band": "B2"},
    {"fname": "master_band_3", "type": "intensity", "band": "B3"},
    {"fname": "master_band_4", "type": "intensity", "band": "B4"},
    {"fname": "master_band_5", "type": "intensity", "band": "B5"},
    {"fname": "master_band_6", "type": "intensity", "band": "B6"},
    {"fname": "master_band_7", "type": "intensity", "band": "B7"},
]

# MANDATORY: Output filenames used by Assembler
tnsr_fnames = {
    "full": {
        "tnsr": "full_tnsr.npy",
        "bad": "full_bd.npy",
        "hdr": "full_tnsr.npy.hdr",
        "meta": "full_tnsr.json",
    },
    "zone": {
        "tnsr": "zone_tnsr.npy",
        "bad": "zone_bd.npy",
        "hdr": "zone_tnsr.npy.hdr",
        "meta": "zone_tnsr.json",
    },
}

# MANDATORY: Minimum spatial tile overlap in pixels
tnsr_tile_min_overlap = 10

# MANDATORY, OVERRIDDEN: Zone extents from recipe
zone = ((1000, 1000), (5000, 5000))

# RECOMMENDED: Overridden by Assembler with the selected product from recipe
products = {
    "truecolor": {
        "filter_kind": None,
        "filter_parameters": [],
    }
}
recipe = {}

COMPOSITE_BANDS = {
    "truecolor": ("B4", "B3", "B2"),
    "infrared": ("B5", "B4", "B3"),
    "vegetation": ("B6", "B5", "B2"),
    "urban": ("B7", "B6", "B4"),
    "water": ("B5", "B6", "B4"),
    "geo": ("B7", "B6", "B2"),
}


def clip_log(img, minlog, maxlog):
    minval = 10 ** minlog
    maxval = 10 ** maxlog
    bad_pixels = (~np.isfinite(img)) | (img < minval) | (img > maxval)
    img = img.astype(np.float32, copy=True)
    img[~np.isfinite(img)] = minval
    img = np.log10(np.clip(img, minval, maxval))
    return img, bad_pixels


def prepare_sigma_scaled(img, fltr):
    img, bad = clip_log(img, 0.0, 6.0)
    img = fltr.apply(img)
    return img, bad


def before(assembler):
    ocli_assert(
        len(products) == 1,
        f'"products" section in recipe has to contain exactly one entry, '
        f"describing the requested product. Got {len(products)} entries instead",
    )
    product_name, product_params = tuple(products.items())[0]
    available_products = tuple(COMPOSITE_BANDS.keys())
    ocli_assert(
        product_name in available_products,
        f"Product name has to be among the available options: "
        f'{available_products}. Got "{product_name}" instead',
    )
    for p in ("filter_kind", "filter_parameters"):
        ocli_assert(p in product_params, f'"{p}" has to be among the product parameters')


def assemble_kernel(inputs, outputs, bad_pixels):
    product_name, _ = tuple(products.items())[0]
    red_band, green_band, blue_band = COMPOSITE_BANDS[product_name]

    task_meta = recipe.get("meta", {}).get("task", {})
    fltr = Filter(
        task_meta.get("denoising.sigma.algorithm"),
        task_meta.get("denoising.sigma.parameters", []),
    )

    red_in = inputs.get(band=red_band)[0]["img"]
    alpha = red_in > 0
    red, bad = prepare_sigma_scaled(red_in, fltr)
    bad_pixels.append(bad)

    green_in = inputs.get(band=green_band)[0]["img"]
    alpha &= green_in > 0
    green, bad = prepare_sigma_scaled(green_in, fltr)
    bad_pixels.append(bad)

    blue_in = inputs.get(band=blue_band)[0]["img"]
    alpha &= blue_in > 0
    blue, bad = prepare_sigma_scaled(blue_in, fltr)
    bad_pixels.append(bad)

    outputs.append(red, name="red")
    outputs.append(green, name="green")
    outputs.append(blue, name="blue")
    outputs.append(alpha.astype(np.float32), name="alpha")
