from pathlib import Path

from pygeai.cli.commands import Option
from pygeai.core.common.exceptions import MissingRequirementException
from pygeai.core.utils.console import Console
from pygeai.skills import SkillsEngine


def validate_skill(option_list: list = None):
    """Validate skill directory structure and SKILL.md format."""
    opts = {opt.name: arg for opt, arg in option_list} if option_list else {}

    skill_path = opts.get("path")
    if not skill_path:
        raise MissingRequirementException(
            "Skill path is required. Use --path <directory>"
        )

    path = Path(skill_path)
    if not path.exists():
        Console.write_error(f"Path does not exist: {skill_path}")
        return

    if not path.is_dir():
        Console.write_error(f"Path is not a directory: {skill_path}")
        return

    engine = SkillsEngine()
    is_valid, errors = engine.validate_skill(path)

    if is_valid:
        Console.write_success(f"✓ Skill at '{skill_path}' is valid!")

        skill = engine.load_skill(path)
        if skill:
            Console.write_stdout(f"\nSkill: {skill.name}")
            Console.write_stdout(f"Description: {skill.description}")
            Console.write_stdout(f"Category: {skill.category}")
            Console.write_stdout(f"Version: {skill.version}")
    else:
        Console.write_error(f"✗ Skill validation failed:\n")
        for error in errors:
            Console.write_error(f"  - {error}")


validate_options = [
    Option("path", ["--path", "-p"], "Path to skill directory", True),
]
