from __future__ import annotations

from pathlib import Path

from juist.justfiles.discovery import JuistDiscovery
from juist.justfiles.models import JuistConfig, Scope, Source
from juist.justfiles.parser import JustfileParser


class JuistLoader:
    """Discovers and parses justfiles into a JuistConfig."""

    def __init__(self, discovery: JuistDiscovery | None = None, parser: JustfileParser | None = None) -> None:
        self._discovery = discovery or JuistDiscovery()
        self._parser = parser or JustfileParser()

    def load(self, cwd: Path | None = None, juist_home: Path | None = None) -> JuistConfig:
        """Discover all justfiles and return a parsed JuistConfig.

        Args:
            cwd: Local directory to scan. Defaults to the current working directory.
            juist_home: Global home directory. Defaults to $JUIST_HOME or ~/.juist.
        """
        paths = self._discovery.discover(cwd=cwd, juist_home=juist_home)
        return JuistConfig(
            global_sources=self._parse_all(paths.global_paths, Scope.global_),
            local_sources=self._parse_all(paths.local_paths, Scope.local),
        )

    def _parse_all(self, paths: list[Path], scope: Scope) -> list[Source]:
        return [self._parser.parse(p, scope) for p in paths]
