"""Workflow for updating mod configuration values and regenerating .cfg overrides."""

from core import constants
from core.io import json_store as storage
from core.io.cfg_format import delete_cfg, generate_overrides


def update_configuration_workflow(form_data: dict[str, str]) -> list[str]:
    """It handles the backup of form data and the regeneration of the associated .cfg files."""
    updated_mods = storage.save_form_values_to_manifests(form_data)

    for mod_id in updated_mods:
        manifest = storage.get_or_create_manifest(constants.REPOSITORY / mod_id, mod_id)
        generate_overrides(mod_id, manifest)

    return updated_mods


def remove_cfg_workflow(mod_id: str, cfg_path: str) -> None:
    """Coordinates the separation of a .cfg file from the JSON and the physical deletion of local files."""
    if not cfg_path:
        return

    was_updated = storage.unlink_cfg_from_manifest(mod_id, cfg_path)

    if was_updated:
        delete_cfg(mod_id=mod_id, cfg_path=cfg_path)


def save_mod_commands_workflow(commands_data: dict[str, str]) -> None:
    """Cleans up and updates the config.json file."""
    if not commands_data:
        return

    config_data = storage.load_config()

    if "mod_commands" not in config_data:
        config_data["mod_commands"] = {}

    for mod_id, raw_commands in commands_data.items():
        mod_key_clean = mod_id.strip().lower()
        cleaned_list = [cmd.strip() for cmd in raw_commands.split(";") if cmd.strip()]
        config_data["mod_commands"][mod_key_clean] = cleaned_list

    storage.save_config(config_data)
