import os
import warnings
from pathlib import Path
from typing import Optional

from commitizen import defaults, git, out
from .base_config import BaseConfig
from .toml_config import TomlConfig
from .ini_config import IniConfig


NOT_A_GIT_PROJECT = 10


def load_global_conf() -> Optional[IniConfig]:
    home = str(Path.home())
    global_cfg = os.path.join(home, ".cz")
    if not os.path.exists(global_cfg):
        return None

    # global conf doesnt make sense with commitizen bump
    # so I'm deprecating it and won't test it
    message = (
        "Global conf will be deprecated in next major version. "
        "Use per project configuration. "
        "Remove '~/.cz' file from your conf folder."
    )
    warnings.simplefilter("always", DeprecationWarning)
    warnings.warn(message, category=DeprecationWarning)

    with open(global_cfg, "r") as f:
        data = f.read()

    conf = IniConfig(data)
    return conf


def read_cfg() -> BaseConfig:
    conf = BaseConfig()

    git_project_root = git.find_git_project_root()
    if not git_project_root:
        out.error(
            "fatal: not a git repository (or any of the parent directories): .git"
        )
        raise SystemExit(NOT_A_GIT_PROJECT)

    allowed_cfg_files = defaults.config_files
    cfg_paths = (
        str(path / Path(filename))
        for path in [Path("."), git_project_root]
        for filename in allowed_cfg_files
    )
    for filename in cfg_paths:
        config_file_exists = os.path.exists(filename)
        if not config_file_exists:
            continue

        with open(filename, "r") as f:
            data: str = f.read()

        if "toml" in filename:
            _conf = TomlConfig(data=data, path=filename)
        else:
            warnings.warn(
                ".cz, setup.cfg, and .cz.cfg will be deprecated "
                "in next major version. \n"
                'Please use "pyproject.toml", ".cz.toml" instead'
            )
            _conf = IniConfig(data=data, path=filename)

        if _conf.is_empty_config:
            continue
        else:
            conf = _conf
            break

    if not conf.path:
        global_conf = load_global_conf()
        if global_conf:
            conf = global_conf

    return conf

@@ -1,14 +1,4 @@
-import os%0A
 impo
@@ -296,20 +296,16 @@
  home = 
-str(
 Path.hom
@@ -307,17 +307,16 @@
 h.home()
-)
 %0A    glo
@@ -329,27 +329,20 @@
 g = 
-os.path.join(home, 
+home / Path(
 %22.cz
@@ -355,31 +355,16 @@
  if not 
-os.path.exists(
 global_c
@@ -365,16 +365,24 @@
 obal_cfg
+.exists(
 ):%0A     
@@ -1270,12 +1270,8 @@
     
-str(
 path
@@ -1287,17 +1287,16 @@
 ilename)
-)
 %0A       
@@ -1429,87 +1429,32 @@
     
-config_file_exists = os.path.exists(filename)%0A        if not config_file_
+if not filename.
 exists
+()
 :%0A  
@@ -1542,24 +1542,24 @@
 = f.read()%0A%0A
-
         if %22
@@ -1575,16 +1575,23 @@
 filename
+.suffix
 :%0A      

replace string type path with pathlib.Path