# OWSplitPath.py
from __future__ import annotations

from pathlib import Path
from typing import Tuple
import sys
import numpy as np
from AnyQt.QtWidgets import QApplication, QCheckBox
from Orange.data import StringVariable
from Orange.widgets.settings import Setting
import os
if "site-packages/Orange/widgets" in os.path.dirname(os.path.abspath(__file__)).replace("\\", "/"):
    from Orange.widgets.orangecontrib.AAIT.utils.initialize_from_ini import apply_modification_from_python_file
    from Orange.widgets.orangecontrib.AAIT.utils import base_widget
else:
    from orangecontrib.AAIT.utils.initialize_from_ini import apply_modification_from_python_file
    from orangecontrib.AAIT.utils import  base_widget





# =========================
# Widget
# =========================
@apply_modification_from_python_file(filepath_original_widget=__file__)
class OWSplitPath(base_widget.BaseListWidget):
    name = "Split Path"
    description = "Normalize path (resolve) and split into directory and file name."
    icon = "icons/split_path.png"
    if "site-packages/Orange/widgets" in os.path.dirname(os.path.abspath(__file__)).replace("\\", "/"):
        icon = "icons_dev/split_path.png"
    category = "AAIT - TOOLBOX"

    gui = os.path.join(os.path.dirname(os.path.abspath(__file__)), "designer/owsplitpath.ui")
    want_control_area = False
    priority = 100
    # Settings
    autorun = Setting(True)

    def _safe_str(self,x) -> str:
        if x is None:
            return ""
        try:
            if isinstance(x, float) and np.isnan(x):
                return ""
        except Exception:
            pass
        return str(x)

    def normalize_path(self,p: str) -> str:
        """Normalize a path using pathlib.resolve(strict=False)."""
        s = self._safe_str(p).strip()
        if not s:
            return ""

        try:
            return Path(s).expanduser().resolve(strict=False).as_posix()
        except Exception:
            # fallback: return raw string if pathlib fails
            return s

    def split_dir_file(self,p: str) -> Tuple[str, str]:
        if not p:
            return "", ""
        try:
            pp = Path(p)
            return pp.parent.as_posix(), pp.name
        except Exception:
            return "", p



    def __init__(self):
        super().__init__()
        self.setFixedWidth(470)
        self.setFixedHeight(500)
        self.data = None
        self.checkbox_mode = self.findChild(QCheckBox, 'checkBox_send')
        self.checkbox_mode.setChecked(self.autorun)
        self.checkbox_mode.stateChanged.connect(self.toogle_persistent)
        self.pushButton_send.clicked.connect(self.run)

    def run(self):
        self.warning("")
        self.error("")

        if self.data is None:
            self.Outputs.data.send(None)
            return
        if not self.selected_column_name in self.data.domain:
            self.warning(f'Previously selected column "{self.selected_column_name}" does not exist in your data.')
            return
        if "path_dir"  in self.data.domain:
            self.error('cannot be used with "path_dir" in input')
            return
        if "file_name"  in self.data.domain:
            self.error('cannot be used with "file_name" in input')
            return
        list_dir=[]
        name_path=[]
        for i, row in enumerate(self.data):
            current_path=str(row[self.selected_column_name].value)
            raw = self._safe_str(current_path)
            norm = self.normalize_path(raw)
            d, name = self.split_dir_file(norm)
            list_dir.append(d)
            name_path.append(name)



        # Generate new Domain to add to data
        list_dir_column = StringVariable("path_dir")
        name_path_column = StringVariable("file_name")

        out_put_data=self.data.copy()
        # Add columns to the table
        out_put_data=out_put_data.add_column(list_dir_column, list_dir, to_metas=True)
        out_put_data=out_put_data.add_column(name_path_column, name_path, to_metas=True)
        self.Outputs.data.send(out_put_data)

    def toogle_persistent(self, enabled):
        if self.checkbox_mode.isChecked():
            self.autorun = True
        else:
            self.autorun = False

if __name__ == "__main__":
    app = QApplication(sys.argv)
    my_widget = OWSplitPath()
    my_widget.show()
    if hasattr(app, "exec"):
        app.exec()
    else:
        app.exec_()
