from pathlib import Path
from typing import Any

from agentmux.adapters.base import ConvertedFile, ToolAdapter
from agentmux.core.component import Agent, Command, Component, Instructions, MCPConfig, Rule, Skill
from agentmux.utils.frontmatter import dump as dump_frontmatter
from agentmux.utils.symlink import sanitize_component_name


class CursorAdapter(ToolAdapter):
    @property
    def name(self) -> str:
        return "cursor"

    def detect(self) -> bool:
        return Path.home().joinpath(".cursor").exists()

    def get_global_base_dir(self) -> Path:
        return Path.home() / ".cursor"

    def get_project_subdir(self) -> Path:
        return Path(".cursor")

    def validate(self, component: Component) -> list[str]:
        return []

    def convert_agent(self, agent: Agent) -> list[ConvertedFile]:
        meta: dict[str, Any] = {
            "name": agent.name,
            "description": agent.description,
            **agent.extra_meta,
        }
        content = dump_frontmatter(meta, agent.body) + "\n"
        safe_name = sanitize_component_name(agent.name)
        return [
            ConvertedFile(
                path=Path("agents") / f"{safe_name}.md",
                content=content,
                source=None,  # always transformed — raw source may have different frontmatter
                scope="global",
            )
        ]

    def convert_command(self, command: Command) -> list[ConvertedFile]:
        filename = command.source_path.name if command.source_path else f"{command.name}.md"
        return [
            ConvertedFile(
                path=Path("commands") / filename,
                content=command.body + "\n",
                scope="global",
            )
        ]

    def convert_skill(self, skill: Skill) -> list[ConvertedFile]:
        dir_name = skill.source_dir.name if skill.source_dir else skill.name
        return [
            ConvertedFile(
                path=Path("skills") / dir_name,
                content=None,
                source=skill.source_dir,
                is_directory=True,
                scope="global",
            )
        ]

    def convert_rule(self, rule: Rule) -> list[ConvertedFile]:
        meta: dict[str, Any] = {"alwaysApply": rule.always_apply}
        if rule.description:
            meta["description"] = rule.description
        if rule.globs:
            meta["globs"] = rule.globs
        content = dump_frontmatter(meta, rule.body) + "\n"
        safe_name = sanitize_component_name(rule.name)
        return [
            ConvertedFile(
                path=Path("rules") / f"{safe_name}.mdc",
                content=content,
                source=None,  # always transformed — target is .mdc, source is .md
                scope="project",
            )
        ]

    def convert_instructions(self, instructions: Instructions) -> list[ConvertedFile]:
        content = dump_frontmatter({"alwaysApply": True}, instructions.body) + "\n"
        return [
            ConvertedFile(
                path=Path("rules") / "instructions.mdc",
                content=content,
                source=None,  # always transformed — adds alwaysApply frontmatter
                scope="project",
            )
        ]

    def convert_mcp(self, mcp: MCPConfig) -> list[ConvertedFile]:
        if mcp.source_path is not None:
            return [
                ConvertedFile(
                    path=Path("mcp.json"),
                    content=None,
                    source=mcp.source_path,
                    scope="global",
                )
            ]
        return [
            ConvertedFile(
                path=Path("mcp.json"),
                content=mcp.to_json(),
                scope="global",
            )
        ]
