#  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.

from __future__ import annotations

import copy
import json
import os
from glob import glob
from typing import Any, Dict, Mapping, Optional, Tuple
from urllib.parse import urlparse

from pydantic import BaseModel, ConfigDict, validate_call

import ocli.core.restricted_value as rv
from ocli.core.exception import OCLIException
from ocli.core.logging_tools import log
from ocli.core.time_types import parse_dt_optional_u
from ocli.finders.finder_creodias_landsat_8 import SatDefaultsLANDSAT8
from ocli.finders.finder_creodias_models import parse_range
from ocli.finders.finder_planetarycomputer import FinderPlanetaryComputer


def _as_bool(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    if isinstance(value, str):
        return value.strip().lower() in ("true", "1", "yes")
    return bool(value)


class SatDefaultsPlanetaryComputerLANDSAT8:
    default_search_params = {
        "cloudCover": rv.TYPED_OPT(str, "100", "cloudCover (less than %)"),
        "processingLevel": rv.ENUM((None, "L2SP", "L2SR"), None, "processingLevel"),
        "collectionCategory": rv.ENUM((None, "T1", "T2"), None, "collectionCategory"),
        "includeThermalAux": rv.ENUM(
            (False, True, "false", "true", "False", "True"),
            False,
            "includeThermalAux",
        ),
    }


class PlanetaryComputerLandsat8ParsedFeature(BaseModel):
    model_config = ConfigDict(extra="allow")

    geometry: Optional[Any] = None
    product_eodata_path: str = ""
    title: str = ""
    productId: str = ""
    stac_item_id: str = ""
    stac_collection: str = "landsat-c2-l2"
    startDate: Optional[Any] = None
    completionDate: Optional[Any] = None
    productType: str = ""
    processingLevel: str = ""
    l8name: str = ""
    satelliteName: str = "landsat-8"
    relativeOrbitNumber: int = -1
    wrs_path: str = ""
    wrs_row: str = ""
    thumbnail_url: str = ""
    cloud_cover: float = 0.0
    sun_azimuth: Optional[float] = None
    sun_elevation: Optional[float] = None
    collection_category: str = ""
    landsat_instrument_code: Optional[str] = None
    landsat_level_code: Optional[str] = None
    landsat_collection: Optional[str] = None
    assets_json: str = "{}"


class FinderPlanetaryComputerLANDSAT8(FinderPlanetaryComputer):
    """Finder for Landsat-8 Collection 2 Level-2 products via Microsoft Planetary Computer STAC API."""

    sat_family_name = "landsat_8"
    collection_name = "landsat-c2-l2"
    l8_search_params = SatDefaultsPlanetaryComputerLANDSAT8.default_search_params

    METADATA_ASSET_KEYS: Tuple[str, ...] = ("mtl.txt", "mtl.xml", "mtl.json", "ang")
    DATA_ASSET_KEYS: Tuple[str, ...] = (
        "coastal",
        "blue",
        "green",
        "red",
        "nir08",
        "swir16",
        "swir22",
        "lwir11",
        "qa_pixel",
        "qa_radsat",
        "qa_aerosol",
        "qa",
    )
    THERMAL_AUX_ASSET_KEYS: Tuple[str, ...] = (
        "atran",
        "cdist",
        "drad",
        "emis",
        "emsd",
        "trad",
        "urad",
    )

    def __init__(
        self,
        eodata_home: str,
        cache_dir: str,
        include_thermal_aux: bool = False,
    ):
        super().__init__(eodata_home=eodata_home, cache_dir=cache_dir)
        self.search_defaults.update(copy.deepcopy(self.l8_search_params))
        if include_thermal_aux:
            self.search_defaults["includeThermalAux"].value = True
        self.cache_path = os.path.join(
            cache_dir, "finders", "planetarycomputer_l8_l2.gpkg"
        )

    def stac_collections(self, params: Mapping[str, Any]) -> list[str]:
        return [self.collection_name]

    def build_query_filter(self, params: Mapping[str, Any]) -> Dict[str, Any]:
        query: Dict[str, Any] = {
            "platform": {"eq": "landsat-8"},
        }

        cloud_cover = params.get("cloudCover")
        if cloud_cover is not None and cloud_cover != "":
            parsed = parse_range(cloud_cover)
            if parsed is not None:
                vmin, vmax = parsed
                cc_filter: Dict[str, Any] = {}
                if vmin is not None and vmin != "" and float(vmin) > 0:
                    cc_filter["gte"] = vmin
                if vmax is not None and vmax != "" and float(vmax) < 100:
                    cc_filter["lte"] = vmax
                if cc_filter:
                    query["eo:cloud_cover"] = cc_filter

        level = params.get("processingLevel")
        if level:
            query["landsat:correction"] = {"eq": str(level).upper()}

        category = params.get("collectionCategory")
        if category:
            query["landsat:collection_category"] = {"eq": str(category).upper()}

        return query

    def select_assets_for_download(
        self, assets: Mapping[str, str], with_measurements: bool = True
    ) -> Dict[str, str]:
        allowed_keys = set(self.METADATA_ASSET_KEYS)
        if with_measurements:
            allowed_keys.update(self.DATA_ASSET_KEYS)
            if _as_bool(self.search_defaults["includeThermalAux"].value):
                allowed_keys.update(self.THERMAL_AUX_ASSET_KEYS)

        return {
            key: href
            for key, href in assets.items()
            if key in allowed_keys and self._is_azure_blob_url(href)
        }

    @classmethod
    def parsed_feature_model(cls) -> type[PlanetaryComputerLandsat8ParsedFeature]:
        return PlanetaryComputerLandsat8ParsedFeature

    @classmethod
    def _extract_product_title(
        cls, item_id: str, blob_assets: Mapping[str, str]
    ) -> str:
        """Derive full 7-part USGS product title from blob directory name when available."""
        preferred_href = blob_assets.get("mtl.txt") or next(iter(blob_assets.values()), None)
        if preferred_href:
            parent_dir = os.path.basename(os.path.dirname(urlparse(preferred_href).path))
            if parent_dir and parent_dir.upper().startswith(("LC08_", "LO08_", "LT08_")):
                return parent_dir
        return item_id

    @classmethod
    @validate_call(validate_return=True)
    def parse_feature(
        cls, feature: Mapping[str, Any]
    ) -> PlanetaryComputerLandsat8ParsedFeature:
        item_id = str(feature.get("id") or "")
        collection = str(feature.get("collection") or cls.collection_name)
        props = feature.get("properties") or {}
        assets = feature.get("assets") or {}

        blob_assets: Dict[str, str] = {}
        for asset_key, asset_obj in assets.items():
            href = asset_obj.get("href") if isinstance(asset_obj, Mapping) else None
            if href and cls._is_azure_blob_url(href):
                blob_assets[asset_key] = href

        title = cls._extract_product_title(item_id, blob_assets)

        try:
            product_spec = SatDefaultsLANDSAT8.product_title_to_dict(title)
        except OCLIException as e:
            log.debug(f"Could not parse 7-part Landsat title '{title}': {e}")
            parts = title.upper().split("_")
            product_spec = {
                "landsat_instrument_code": parts[0] if len(parts) > 0 and parts[0] else None,
                "landsat_level_code": props.get("landsat:correction")
                or (parts[1] if len(parts) > 1 else None),
                "landsat_collection": props.get("landsat:collection_number"),
            }

        start_dt = parse_dt_optional_u(props.get("start_datetime") or props.get("datetime"))
        end_dt = parse_dt_optional_u(props.get("end_datetime") or props.get("datetime"))

        level_code = str(
            props.get("landsat:correction")
            or product_spec.get("landsat_level_code")
            or "L2SP"
        ).upper()

        if start_dt is not None:
            date_subpath = start_dt.strftime("%Y/%m/%d")
        else:
            date_subpath = "unknown_date"

        product_eodata_path = f"Landsat-8/OLI_TIRS/{level_code}/{date_subpath}/{title}"

        wrs_path = str(props.get("landsat:wrs_path") or "")
        wrs_row = str(props.get("landsat:wrs_row") or "")
        try:
            rel_orbit = int(wrs_path) if wrs_path else -1
        except ValueError:
            rel_orbit = -1

        preview_asset = assets.get("rendered_preview")
        thumbnail_url = (
            preview_asset.get("href", "") if isinstance(preview_asset, Mapping) else ""
        )

        platform = str(props.get("platform") or "landsat-8")

        return PlanetaryComputerLandsat8ParsedFeature(
            geometry=cls.parse_geometry(feature.get("geometry")),
            product_eodata_path=product_eodata_path,
            title=title,
            productId=SatDefaultsLANDSAT8.product_title_to_id(title),
            stac_item_id=item_id,
            stac_collection=collection,
            startDate=start_dt,
            completionDate=end_dt,
            productType=level_code.lower(),
            processingLevel=level_code.lower(),
            l8name=SatDefaultsLANDSAT8.normalize_l8name(platform),
            satelliteName=platform.lower(),
            relativeOrbitNumber=rel_orbit,
            wrs_path=wrs_path,
            wrs_row=wrs_row,
            thumbnail_url=thumbnail_url,
            cloud_cover=float(props.get("eo:cloud_cover") or 0.0),
            sun_azimuth=props.get("view:sun_azimuth"),
            sun_elevation=props.get("view:sun_elevation"),
            collection_category=str(props.get("landsat:collection_category") or ""),
            landsat_instrument_code=product_spec.get("landsat_instrument_code"),
            landsat_level_code=product_spec.get("landsat_level_code") or level_code,
            landsat_collection=product_spec.get("landsat_collection")
            or props.get("landsat:collection_number"),
            assets_json=json.dumps(blob_assets),
        )

    def check_product_in_eodata(self, title_or_id: str) -> Tuple[bool, bool]:
        local_path, _ = self._get_local_and_remote_path(title_or_id)
        loaded = any(glob(os.path.join(local_path, "*_MTL.txt")))
        with_data = any(glob(os.path.join(local_path, "*.TIF")))
        return loaded, with_data
