import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const pluginName = "needle-ai";

/**
 * Needle Engine Claude skill installer.
 *
 * Writes a Needle Engine skill to `.claude/skills/needle-engine/SKILL.md`.
 * Claude Code auto-loads skills based on their description frontmatter, so
 * Claude will automatically have Needle Engine context when working in the project.
 *
 * The skill is only written if `.claude/` already exists in the project root
 * (i.e. the developer is already using Claude Code). Old skill files are
 * always overwritten so the skill stays up to date with the engine version.
 *
 * @param {"build" | "serve"} command
 * @param {{} | undefined | null} config
 * @param {import('../types/index.js').userSettings} userSettings
 * @returns {import('vite').Plugin | null}
 */
export function needleAI(command, config, userSettings) {
    return {
        name: pluginName,
        enforce: "pre",
        buildStart() {
            installClaudeSkill();
        },
        configureServer() {
            installClaudeSkill();
        },
    };
}

function writeSkill(claudeDir) {
    const skillDir = join(claudeDir, "skills", "needle-engine");
    if (!existsSync(skillDir)) {
        mkdirSync(skillDir, { recursive: true });
    }
    const skillPath = join(skillDir, "SKILL.md");
    const templatePath = join(__dirname, "../../SKILL.md");
    const content = readFileSync(templatePath, "utf8");
    writeFileSync(skillPath, content, "utf8");
    return skillPath;
}

function installClaudeSkill() {
    const claudeDir = join(process.cwd(), ".claude");
    if (!existsSync(claudeDir)) return; // only install if developer uses Claude Code

    const path = writeSkill(claudeDir);
    console.log(`[${pluginName}] Installed Needle Engine Claude skill → ${path}`);
}
