#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Personal functions to aid on multiple scripts"""
import sys
import fileinput
import re
import os
import logging
import shlex
import subprocess
import shutil
import random
from typing import Sequence
from pathlib import Path
import yaml

VERBOSE_G = False

LOG = logging.getLogger()
HANDLER = logging.StreamHandler()
FORMATTER = logging.Formatter(
    "[%(filename)s][%(levelname)s] %(funcName)s '%(message)s'"
)
HANDLER.setFormatter(FORMATTER)
LOG.addHandler(HANDLER)
LOG.setLevel(logging.INFO)


def validate_x_link(line: str) -> str:
    """returns a fixed link, which ends with /media"""
    # if url contains /media at the end just write the line
    if re.search(r"\/media$", line):
        return line
    # if does not contain /media at the end then add /media
    return f"{line}/media"


def parse_link(link: str) -> str:
    """Fixes links"""
    if not re.search(r"(x\.com\/\w+(\/)?(?!.*status))", link):
        LOG.debug("No modifications needed for the link %s", link)
        return link
    # if url contains /media at the end just write the line
    fixed_link = validate_x_link(link)
    LOG.debug("Processed link %s", fixed_link)
    return fixed_link


def load_config_variables():
    """Loads all the variables from the config file"""
    config_file = Path("~/.config/jawz/config.yaml")
    with open(config_file.expanduser(), encoding="utf-8") as open_file:
        return yaml.safe_load(open_file)


def clean_cache(directory: Path):
    """Recursively deletes all the content of a directory,
    including the directory itself."""
    if not directory.is_dir():
        return
    shutil.rmtree(directory)


def run(
    command: str | Sequence[str],
    verbose: bool,
    cwd: Path | None = None,
    check: bool = False,
    on_line=None,
    log_failure: bool = True,
) -> None:
    """Run command in a subprocess"""
    # pylint: disable=subprocess-run-check
    # This toggle allows for a really wasy debug when using -v
    if verbose:
        if isinstance(command, (list, tuple)):
            print(shlex.join(command))
        else:
            print(command)
        return

    if isinstance(command, str):
        expanded = os.path.expandvars(command)
        args = shlex.split(expanded)
    else:
        args = list(command)

    if on_line is None:
        result = subprocess.run(args, check=check, cwd=cwd)
        if log_failure and not check and result.returncode != 0:
            LOG.warning("Command failed (%s): %s", result.returncode, args)
        return

    proc = subprocess.Popen(
        args,
        cwd=cwd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )
    assert proc.stdout is not None
    for line in proc.stdout:
        print(line, end="")
        on_line(line)
    returncode = proc.wait()
    if check and returncode != 0:
        raise subprocess.CalledProcessError(returncode, args)
    if log_failure and not check and returncode != 0:
        LOG.warning("Command failed (%s): %s", returncode, args)


def list_lines(i: int, line: str) -> str:
    """Create a numbered list"""
    return f"{i}) {line}"




def sort_txt_file(file_path: Path):
    """Sort every line alphabetically
    remove duplicated and empty lines"""
    path = file_path.resolve()
    with open(path, "r", encoding="utf-8") as open_file:
        lines = [ln.strip() for ln in open_file]

    normalized = []
    for ln in lines:
        if not ln:
            continue
        ln = ln.replace("http://", "https://")
        ln = ln.rstrip("/")
        normalized.append(ln)

    unique_sorted = sorted(set(normalized))
    with open(path, "w", encoding="utf-8") as open_file:
        open_file.write("\n".join(unique_sorted))
        if unique_sorted:
            open_file.write("\n")


def randomize_txt_file(file_path: Path):
    """Randomize the order of the
    lines of the txt file"""
    path = file_path.resolve()
    with open(path, "r", encoding="utf-8") as open_file:
        lines = [ln.rstrip("\n") for ln in open_file]
    random.shuffle(lines)
    with open(path, "w", encoding="utf-8") as open_file:
        open_file.write("\n".join(lines))
        if lines:
            open_file.write("\n")


def parse_list(file):
    """Replace http with https and remove trailing /"""
    for line in fileinput.input(file, inplace=True):
        sys.stdout.write(str(line).replace("http://", "https://"))
    with open(file, "r+", encoding="utf-8") as open_file:
        lines = [ln.rstrip("\n").rstrip("/") + "\n" for ln in open_file]
        open_file.seek(0)
        open_file.truncate()
        open_file.writelines(lines)
    sort_txt_file(file)
