"""Symlink setup for non-native harnesses."""

from __future__ import annotations

from pathlib import Path

import click

from .profile import HarnessProfile


def setup_harness(profile: HarnessProfile, project_dir: Path | None = None) -> bool:
    """Create symlinks for a harness in the current project.

    Returns True if any changes were made.
    """
    project = project_dir or Path.cwd()
    claude_dir = project / ".claude"

    if profile.native:
        click.echo(
            click.style(f"{profile.name}", fg="green")
            + " reads .claude/ natively -- no setup needed"
        )
        return False

    if not claude_dir.is_dir():
        click.echo(
            click.style("Error: ", fg="red")
            + ".claude/ directory not found in current project"
        )
        click.echo("Run this from a project with a .claude/ directory.")
        return False

    click.echo(
        click.style(f"Setting up {profile.name}", bold=True)
        + f" ({profile.config_dir}/)"
    )

    config_dir = project / profile.config_dir
    config_dir.mkdir(parents=True, exist_ok=True)
    changes = False

    # Setup skills symlinks (per-skill, not whole directory)
    if profile.skills_dir:
        source_skills = claude_dir / "skills"
        if source_skills.is_dir():
            target_skills = config_dir / profile.skills_dir
            target_skills.mkdir(parents=True, exist_ok=True)
            for skill in source_skills.iterdir():
                if skill.is_dir():
                    link = target_skills / skill.name
                    if not link.exists():
                        # Compute relative path for symlink
                        rel = Path("..") / ".." / ".claude" / "skills" / skill.name
                        link.symlink_to(rel)
                        _log_link(f"{profile.config_dir}/{profile.skills_dir}/{skill.name}", f".claude/skills/{skill.name}", "created")
                        changes = True
                    else:
                        _log_link(f"{profile.config_dir}/{profile.skills_dir}/{skill.name}", "", "exists")

    # Setup context file symlink
    # CLAUDE.md can be in .claude/ or project root -- check both
    if profile.context_target:
        source_in_claude = claude_dir / profile.context_source
        source_in_root = project / profile.context_source
        source = None
        rel = Path(".")
        source_label = ""
        if source_in_claude.exists():
            source = source_in_claude
            rel = Path("..") / ".claude" / profile.context_source
            source_label = f".claude/{profile.context_source}"
        elif source_in_root.exists():
            source = source_in_root
            rel = Path("..") / profile.context_source
            source_label = profile.context_source
        if source:
            target = config_dir / profile.context_target
            if not target.exists():
                target.symlink_to(rel)
                _log_link(
                    f"{profile.config_dir}/{profile.context_target}",
                    source_label,
                    "created",
                )
                changes = True
            else:
                _log_link(f"{profile.config_dir}/{profile.context_target}", "", "exists")

    # Setup MCP config symlink
    if profile.mcp_target:
        mcp_source = project / profile.mcp_source
        if mcp_source.exists():
            target = project / profile.mcp_target
            target.parent.mkdir(parents=True, exist_ok=True)
            if not target.exists():
                rel = Path("..") / profile.mcp_source
                target.symlink_to(rel)
                _log_link(profile.mcp_target, profile.mcp_source, "created")
                changes = True
            else:
                _log_link(profile.mcp_target, "", "exists")

    # Setup explicit symlinks from profile
    for sl in profile.symlinks:
        source = project / sl.source
        target = project / sl.target
        if source.exists() and not target.exists():
            target.parent.mkdir(parents=True, exist_ok=True)
            # Compute relative path
            rel = Path(*(['..'] * len(Path(sl.target).parts[:-1]))) / sl.source
            target.symlink_to(rel)
            _log_link(sl.target, sl.source, "created")
            changes = True
        elif target.exists():
            _log_link(sl.target, "", "exists")

    if changes:
        click.echo(click.style("Done", fg="green"))
    else:
        click.echo(click.style("Nothing to do", fg="yellow") + " -- all symlinks already exist")

    return changes


def _log_link(target: str, source: str, status: str) -> None:
    """Log a symlink operation."""
    if status == "created":
        click.echo(f"  {click.style('+', fg='green')} {target} -> {source}")
    elif status == "exists":
        click.echo(f"  {click.style('=', fg='yellow')} {target} (already exists)")
