"""CLI command: asa apply — apply foundation architecture from .asa/spec.yaml."""

import typer

from ..core import logging as log
from ..core.paths import find_project_root
from ..engine.applier.applier import apply_foundation
from ..engine.spec.parser import load_spec


def apply(
    force: bool = typer.Option(False, "--force", help="Force overwrite existing files"),
) -> None:
    """Apply foundation architecture based on .asa/spec.yaml.

    Reads the spec and installs foundation modules (db-basic, auth-basic,
    payments-basic) plus entitlement architecture. Internally calls
    'asa install' for each module.
    """
    project_root = find_project_root()

    spec = load_spec(project_root)
    if spec is None:
        log.error(
            "No .asa/spec.yaml found. Run 'asa spec infer' or 'asa init' first."
        )
        raise typer.Exit(code=1)

    errors = apply_foundation(project_root, spec, force=force)

    print()
    if errors == 0:
        log.success("Foundation applied. Run 'asa verify' to check architecture.")
    else:
        log.error(f"Apply completed with {errors} errors. Fix and re-run 'asa apply'.")
        raise typer.Exit(code=1)
