import subprocess
from pathlib import Path
from typing import Any

from nicegui import ui

from nemo_library_etl.adapter._utils.enums import ETLStep
from nemo_library_etl.adapter.migman.enums import (
    MigManExtractAdapter,
    MigManLoadAdapter,
)


def resolve_ui_path(path_value: str | Path | None) -> Path | None:
    if path_value is None:
        return None

    raw_value = str(path_value).strip()
    if not raw_value:
        return None

    path = Path(path_value).expanduser()
    if not path.is_absolute():
        path = Path.cwd() / path
    return path.resolve(strict=False)


def open_folder_in_explorer(path_value: str | Path) -> None:
    try:
        path = resolve_ui_path(path_value)
        if path is None or not path.exists() or not path.is_dir():
            return
        subprocess.Popen(["explorer", str(path)])
    except Exception as exc:
        ui.notify(f"Could not open folder: {exc}", type="warning")


def render_folder_button(
    path_value: str | Path | None, tooltip: str | None = None
):
    path = resolve_ui_path(path_value)
    if path is None or not path.exists() or not path.is_dir():
        return None

    button = ui.button(
        icon="folder_open",
        on_click=lambda: open_folder_in_explorer(path),
    ).props("flat round size=sm")
    if tooltip:
        button.tooltip(tooltip)
    return button


def resolve_etl_dir(form_state: dict[str, Any]) -> Path:
    etl_directory = form_state.get("data", {}).get("etl_directory", "./etl/migman")
    return resolve_ui_path(etl_directory) or (Path.cwd() / "etl" / "migman")


def resolve_extract_output_dir(form_state: dict[str, Any]) -> Path:
    etl_dir = resolve_etl_dir(form_state)
    primary_dir = etl_dir / ETLStep.EXTRACT.value
    legacy_dir = etl_dir / "migman" / ETLStep.EXTRACT.value

    if primary_dir.exists():
        return primary_dir
    if legacy_dir.exists():
        return legacy_dir
    return primary_dir


def resolve_join_dir(form_state: dict[str, Any]) -> Path:
    source_adapter = (
        form_state.get("data", {})
        .get("setup", {})
        .get("source_adapter", MigManExtractAdapter.GENERICODBC.value)
    )
    return resolve_ui_path(Path("config") / source_adapter / "joins") or (
        Path.cwd() / "config" / source_adapter / "joins"
    )


def resolve_mapping_dir(form_state: dict[str, Any]) -> Path:
    return resolve_etl_dir(form_state) / "mapping"


def resolve_load_reports_dir(form_state: dict[str, Any]) -> Path:
    target_adapter = (
        form_state.get("data", {})
        .get("setup", {})
        .get("target_adapter", MigManLoadAdapter.PROALPHA_MIGMAN.value)
    )
    report_folder = "to_proalpha"
    if target_adapter == MigManLoadAdapter.NEMO_BUSINESS_PROCESSES.value:
        report_folder = "to_customer"

    return resolve_etl_dir(form_state) / "reports" / report_folder
