"""Validate command - Validate project artifacts.

Contract: CNT-T4-CMD-004
Traceability: UI-002
"""

from pathlib import Path

import click

from laida_cli.services.context_validator import ContextValidator
from laida_cli.services.traceability_checker import TraceabilityChecker
from laida_cli.ui import LaidaConsole, Styles

console = LaidaConsole()


@click.command("validate")
@click.option(
    "--path", "-p",
    type=click.Path(exists=True),
    default=".",
    help="Path to LAIDA project (default: current directory)",
)
@click.option(
    "--context-only",
    is_flag=True,
    help="Only validate project_context.yaml",
)
@click.option(
    "--traceability-only",
    is_flag=True,
    help="Only check traceability",
)
def validate_command(path: str, context_only: bool, traceability_only: bool) -> None:
    """Validate project artifacts.

    Checks:
    - project_context.yaml validity
    - Schema compliance of YAML files
    - Cross-artifact traceability
    """
    project_path = Path(path).resolve()

    # Check if LAIDA project
    if not (project_path / ".laida").exists():
        console.error("Not a LAIDA project. Run 'laida init' first.")
        raise SystemExit(1)

    console.print()
    console.header("LAIDA Validation Report")
    console.print(f"Path: {project_path}")
    console.print()

    has_errors = False

    # Validate context
    if not traceability_only:
        context_errors = _validate_context(project_path)
        if context_errors:
            has_errors = True

    # Check traceability
    if not context_only:
        trace_errors = _check_traceability(project_path)
        if trace_errors:
            has_errors = True

    # Summary
    console.print()
    if has_errors:
        console.error("Validation failed with errors.", prefix="")
        raise SystemExit(1)
    else:
        console.success("All validations passed.")


def _validate_context(project_path: Path) -> bool:
    """Validate project_context.yaml.

    Args:
        project_path: Path to project

    Returns:
        True if there were errors
    """
    console.header("Context Validation")

    validator = ContextValidator()
    result = validator.validate(project_path)

    table = console.create_table("Status", "Message", show_header=False)

    if result.is_valid:
        table.add_row(f"[{Styles.PASS}]PASS[/{Styles.PASS}]", "project_context.yaml is valid")

        for warning in result.warnings:
            table.add_row(f"[{Styles.WARN}]WARN[/{Styles.WARN}]", warning)

        console.print(table)
        return False
    else:
        for error in result.errors:
            table.add_row(f"[{Styles.FAIL}]FAIL[/{Styles.FAIL}]", error)

        console.print(table)
        return True


def _check_traceability(project_path: Path) -> bool:
    """Check cross-artifact traceability.

    Args:
        project_path: Path to project

    Returns:
        True if there were errors
    """
    console.print()
    console.header("Traceability Check")

    checker = TraceabilityChecker()
    report = checker.check_links(project_path)

    table = console.create_table("Status", "Message", show_header=False)

    if report.total_references == 0:
        table.add_row(f"[{Styles.SKIP}]SKIP[/{Styles.SKIP}]", "No artifacts to check (project not started?)")
        console.print(table)
        return False

    if report.is_valid:
        table.add_row(
            f"[{Styles.PASS}]PASS[/{Styles.PASS}]",
            f"All {report.valid_references}/{report.total_references} references valid"
        )
        table.add_row("", f"Coverage: {report.coverage:.1f}%")

        if report.orphan_artifacts:
            table.add_row(
                f"[{Styles.WARN}]WARN[/{Styles.WARN}]",
                f"Orphan artifacts: {', '.join(report.orphan_artifacts[:5])}"
            )

        console.print(table)
        return False
    else:
        table.add_row(
            f"[{Styles.FAIL}]FAIL[/{Styles.FAIL}]",
            f"Broken references: {', '.join(report.broken_references[:5])}"
        )
        console.print(table)
        return True
