"""``sfc skills analyze`` — AI-powered codebase analysis via headless Claude."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from launcher.wrapper import build_env, find_claude_binary

ANALYZE_PROMPT = (
    "Run /sync to analyze this codebase and generate/update project rules and "
    "skills. Work through all 10 phases. Do not ask questions — make reasonable "
    "default choices. When discovering new rules or skills, create them without "
    "confirmation. At the end, output a summary of what was created or updated."
)


def run_analyze(*, dry_run: bool = False, model: str = "sonnet") -> None:
    """Launch headless Claude to run /sync analysis."""
    # Ensure .claude directory exists
    claude_dir = Path.cwd() / ".claude"
    rules_dir = claude_dir / "rules"
    skills_dir = claude_dir / "skills"
    rules_dir.mkdir(parents=True, exist_ok=True)
    skills_dir.mkdir(parents=True, exist_ok=True)

    try:
        claude_bin = find_claude_binary()
    except FileNotFoundError as exc:
        print(str(exc), file=sys.stderr)
        sys.exit(1)

    if dry_run:
        print("Dry run — would execute:")
        print(f"  Binary:  {claude_bin}")
        print(f"  Model:   {model}")
        print(f"  Workdir: {Path.cwd()}")
        print(f"  Prompt:  {ANALYZE_PROMPT[:80]}...")
        return

    env = build_env()

    cmd = [
        claude_bin,
        "--print",
        "--model",
        model,
        "--dangerously-skip-permissions",
        "--output-format",
        "text",
        ANALYZE_PROMPT,
    ]

    print("Analyzing codebase... (this may take a few minutes)")
    print("Using Claude to discover patterns, create rules, and generate skills.")
    print("Note: This grants Claude file read/write access within your project.")
    print()

    result = subprocess.run(cmd, env=env)
    if result.returncode != 0:
        print(
            f"\nAnalysis exited with code {result.returncode}",
            file=sys.stderr,
        )
        sys.exit(result.returncode)
