import os
import platform
import sys
from pathlib import Path

import qgis

from openlog.__about__ import DIR_PLUGIN_ROOT

conf_path = Path(DIR_PLUGIN_ROOT) / "scripts" / ".vars.conf"
sh_path = Path(DIR_PLUGIN_ROOT) / "scripts" / "auto_import.sh"


def check_paths() -> None:
    """
    Update python interpreter folder and current pyqgis path in /scripts/.vars.conf file.
    Also, set auto_import.sh executable.
    """
    try:
        os.chmod(sh_path, 0o755)

        system = platform.system()
        python_path = (
            Path(os.__file__).parents[1]
            if system == "Windows"
            else Path(sys.executable).resolve().parents[0]
        )
        pyqgis_path = Path(qgis.__file__).parents[1]
        updates = {
            "PYTHON_INTERPRETER": str(python_path),
            "PYQGIS_PATH": str(pyqgis_path),
        }

        # if file doesn't exist, create it
        if not conf_path.exists():
            with open(conf_path, "w") as f:
                f.writelines(["PYTHON_INTERPRETER=\n", "PYQGIS_PATH=\n"])

        lines = conf_path.read_text(encoding="utf-8").splitlines()
        out = []
        seen = set()

        for line in lines:
            stripped = line.strip()

            if "=" in line:
                key, _ = line.split("=", 1)
                key = key.strip()

                if key in updates:
                    out.append(f"{key}={updates[key]}")
                    seen.add(key)
                else:
                    out.append(line)
            else:
                out.append(line)

        for k, v in updates.items():
            if k not in seen:
                out.append(f"{k}={v}")

        conf_path.write_text("\n".join(out) + "\n", encoding="utf-8")

    except Exception:
        pass
