import os
from pathlib import Path
import xml.etree.ElementTree as ET

import rich


def exec_gen_qrc(qrc_path: Path, dir_list: list[Path]) -> None:
    with open(qrc_path, "w", encoding="utf-8") as f:
        f.write("<RCC>\n")

        for directory in dir_list:
            if not directory.is_dir():
                continue

            prefix = f"{directory.name}"
            f.write(f'  <qresource prefix="{prefix}">\n')

            for file in directory.rglob("*"):
                if file.is_file():
                    relative_path = file.relative_to(directory.parent)
                    f.write(f'    <file>{relative_path.as_posix()}</file>\n')

            f.write("  </qresource>\n")

        f.write("</RCC>\n")


def exec_gen_res_py(qrc_file_path, output_file_path, main_class_name="ResourcesIds"):
    # Parsing del file .qrc
    tree = ET.parse(qrc_file_path)
    root = tree.getroot()

    # Inizializzazione del contenuto del file
    content = [
        f"class {main_class_name}:",
        "    \"\"\"Class containing all application's resources.\"\"\""
    ]

    # Dizionario per tenere traccia delle risorse per prefix
    prefix_resources = {}

    # Elaborazione delle risorse
    for qresource in root.findall('qresource'):
        prefix = qresource.get('prefix', '')

        # Inizializza la lista per questo prefix se non esiste
        if prefix not in prefix_resources:
            prefix_resources[prefix] = []

        for file_elem in qresource.findall('file'):
            file_path = file_elem.text
            resource_path = f":{prefix}/{file_path}"

            # Crea un nome di variabile adatto
            base_name = os.path.basename(file_path)
            var_name = base_name.replace('.', '_').replace('-', '_').upper()

            # Semplifica il nome della variabile rimuovendo l'estensione
            var_name = var_name.split('.')[0] if '.' in var_name else var_name

            # Aggiungi la risorsa alla lista del prefix corrispondente
            prefix_resources[prefix].append(f"        {var_name} = \"{resource_path}\"")

    # Genera classi per ogni prefix
    for prefix, resources in prefix_resources.items():
        if prefix:
            # Capitalizza il nome della classe
            class_name = prefix.capitalize()

            # Aggiungi la definizione della classe
            content.append("")
            content.append(f"    class {class_name}:")
            content.append(f"        \"\"\"Resource with prefix '{prefix}'\"\"\"")
            content.append("")

            # Aggiungi tutte le risorse per questo prefix
            content.extend(resources)

    # Scrittura del file
    with open(output_file_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(content))

    rich.print(f"Resources id python file generated in: {output_file_path}")


def exec_gen_css_py(css_folder: Path, output_file: Path):
    if not css_folder.is_dir():
        raise ValueError(f"{css_folder} is not a valid directory")

    css_files = css_folder.glob("*.css")
    lines = ["# AUTOGENERATED\n"]

    for css_file in css_files:
        variable_name = css_file.stem  # nome del file senza estensione
        css_content = css_file.read_text(encoding="utf-8")
        lines.append(f"{variable_name} = r'''{css_content}'''\n")

    output_file.write_text("\n".join(lines), encoding="utf-8")