import shutil
from pathlib import Path

from .contacts import Contacts
from .paths import Paths
from .prompt import Prompt
from .settings import Settings


def _ensure_skills_dir(skills_path: Path) -> None:
    skills_path.mkdir(parents=True, exist_ok=True)
    matraca_skills = Path(__file__).parent.parent / "skills"
    for skill in matraca_skills.iterdir():
        if skill.is_dir():
            destination = skills_path / skill.name
            if not destination.exists():
                shutil.copytree(skill, destination)


class Setup:
    def __init__(self) -> None:
        self.paths = Paths()
        self.paths.base_dir.mkdir(parents=True, exist_ok=True)
        self.settings = Settings.ensure(self.paths.settings_path)
        self.contacts = Contacts.ensure(self.paths.contacts_path)
        self.prompt = Prompt.ensure(self.paths.prompt_path)
        self.settings.ensure_environment_variables()
        _ensure_skills_dir(self.paths.skills_path)

    def clear_data(self) -> None:
        for history_file in self.paths.base_dir.glob("*/history.json"):
            history_file.unlink()

        if self.paths.skills_path.exists():
            shutil.rmtree(self.paths.skills_path)

        _ensure_skills_dir(self.paths.skills_path)


def setup_app(
    clear_data: bool = False,
) -> tuple[
    Paths,
    Settings,
    Contacts,
    Prompt,
]:
    setup = Setup()
    if clear_data:
        setup.clear_data()
    return (
        setup.paths,
        setup.settings,
        setup.contacts,
        setup.prompt,
    )
