"""``sfc skills init`` — bootstrap .claude/ with project configuration."""

from __future__ import annotations

import sys
from pathlib import Path

from launcher.skills._project_detector import detect_project
from launcher.skills._templates import render_project_md


def run_init(project_dir: Path | None = None) -> None:
    """Create .claude/ structure with project.md."""
    base = project_dir or Path.cwd()
    rules_dir = base / ".claude" / "rules"
    skills_dir = base / ".claude" / "skills"

    # Create directories
    try:
        rules_dir.mkdir(parents=True, exist_ok=True)
        skills_dir.mkdir(parents=True, exist_ok=True)
    except OSError as exc:
        print(f"Error creating .claude/ directories: {exc}", file=sys.stderr)
        return

    project_md = rules_dir / "project.md"
    if project_md.exists():
        print(f"project.md already exists at {project_md}")
        print("Use 'sfc skills analyze' to update it with AI analysis.")
        return

    # Detect project metadata
    project = detect_project(base)

    # Render and write project.md
    content = render_project_md(project)
    try:
        project_md.write_text(content, encoding="utf-8")
    except OSError as exc:
        print(f"Error writing {project_md}: {exc}", file=sys.stderr)
        return

    print(f"Created {project_md}")
    print()
    print("Detected:")
    if project["languages"]:
        print(f"  Languages:   {', '.join(project['languages'])}")
    if project["frameworks"]:
        print(f"  Frameworks:  {', '.join(project['frameworks'])}")
    if project["package_manager"]:
        print(f"  Pkg Manager: {project['package_manager']}")
    print()
    print("Run 'sfc skills analyze' for AI-powered codebase analysis.")
