"""asa slice sync — Validate and synchronize all contracts."""

import typer

from ...core import logging as log
from ...core.errors import AsaError
from ...core.paths import find_project_root


def run_slice_sync() -> None:
    """Validate all contracts in project and report issues."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.contract.validator import validate_all_contracts
    try:
        project_root = find_project_root()
        results = validate_all_contracts(project_root)

        if not results:
            log.warning("No contracts found in domains/")
            raise typer.Exit(0)

        valid = 0
        invalid = 0

        for path, result in results:
            if isinstance(result, str):
                log.lint_fail(f"{path.parent.parent.name}/{path.parent.name}: {result}")
                invalid += 1
            else:
                valid += 1

        if invalid == 0:
            log.success(f"All contracts valid ({valid} checked)")
            raise typer.Exit(0)
        else:
            log.lint_fail(f"{valid} valid, {invalid} invalid")
            raise typer.Exit(1)

    except AsaError as e:
        log.error(str(e))
        raise typer.Exit(1)
    except typer.Exit:
        raise
    except Exception as e:
        log.error(f"[INTERNAL ERROR] {e}")
        raise typer.Exit(2)
