/**
 * Bootstrap built-in global skills on every mcpd startup.
 *
 * Mirrors `bootstrap/system-project.ts` for prompts: idempotent upserts so
 * deletes + re-creates work, but never overwrites user edits to the skill
 * content. The single skill seeded today is `propose-learnings` — it
 * encourages Claude to actually use the propose_prompt / propose_skill
 * MCP tools when it discovers something worth capturing.
 *
 * The skill lives at global scope (no projectId, no agentId) and gets
 * synced onto every dev machine by `mcpctl skills sync` (PR-5).
 */

import type { PrismaClient } from '@prisma/client';

interface SystemSkillDef {
  name: string;
  description: string;
  priority: number;
  content: string;
}

const PROPOSE_LEARNINGS_CONTENT = `# propose-learnings

This Claude Code session is connected to mcpctl, which keeps a curated
library of project knowledge — patterns, gotchas, conventions, and
policies — and makes that knowledge available to future sessions. Two
tools matter here:

- \`propose_prompt\` — propose a small piece of text knowledge for the
  current project. A reviewer approves it, then it appears for every
  future session on this project as a \`read_prompts\` candidate.
- \`propose_skill\` — propose a Claude Code skill (a SKILL.md). Use this
  only when the knowledge is genuinely cross-cutting (debugging
  discipline, release hygiene, security review style) and would help
  across many projects, not just this one.

## When to engage

Most sessions don't need to propose anything. Engage when one of these
is true and the cost of the next session re-discovering it would be
real:

1. You hit a bug that took non-trivial digging to root-cause, and the
   cause was a project-specific quirk a future you would have benefited
   from knowing in advance ("this codebase shadows \`request\` with
   \`req\` in three files; grep for both").
2. You learned a convention by reading code that wasn't documented
   anywhere ("services live under \`src/mcpd/src/services\` and are
   wired in \`main.ts\` around line 466").
3. The user told you something corrective ("we don't use Prisma
   transactions for migrations here, we use raw SQL files") that would
   otherwise be lost.

## When NOT to engage

- Anything you read in an existing prompt — it's already captured.
- Generic programming advice. Future sessions have the same training
  as you.
- Speculation. Only propose what you actually verified during this
  session.
- Anything secret, anything PII, anything that names a customer.

## How to write a good proposal

Name it \`lowercase-with-hyphens\`. Keep it under 200 words. Lead with
the shape of the situation, not the resolution — future-you needs to
recognise when this applies. Example:

> name: prisma-null-fk-workaround
> content: When a Prisma model has an optional FK that's part of a
> compound \`@@unique\`, Postgres treats NULL as distinct, so duplicates
> sneak in. Workaround in this repo: store empty string instead of NULL
> for the FK and use \`?? ''\` at every read site. See
> \`src/mcpd/src/repositories/prompt.repository.ts:75\` for the pattern.

## How proposals get applied

Proposals enter a queue. A maintainer runs \`mcpctl review next\`, sees
a diff, and either approves (the prompt or skill goes live for the next
session) or rejects with a note. You will not see the outcome in this
session. That's fine — the system is designed so individual sessions
don't need to follow up.

If you're unsure whether something is worth proposing, lean toward yes
for prompts (cheap to add, easy to reject) and lean toward no for
skills (harder to scope, larger blast radius).
`;

const SYSTEM_SKILLS: SystemSkillDef[] = [
  {
    name: 'propose-learnings',
    description:
      'How and when to use propose_prompt / propose_skill to capture project knowledge for future sessions.',
    priority: 9,
    content: PROPOSE_LEARNINGS_CONTENT,
  },
];

/**
 * Ensure system-owned global skills exist. Safe to call on every startup.
 * If a user has edited or deleted a system skill, we leave their edit
 * alone — same policy as system-project.ts.
 */
export async function bootstrapSystemSkills(prisma: PrismaClient): Promise<void> {
  for (const def of SYSTEM_SKILLS) {
    const existing = await prisma.skill.findFirst({
      where: { name: def.name, projectId: null, agentId: null },
    });
    if (existing === null) {
      await prisma.skill.create({
        data: {
          name: def.name,
          description: def.description,
          priority: def.priority,
          content: def.content,
          // semver/files/metadata default to schema defaults.
        },
      });
    }
    // If it exists, leave the user's edits alone.
  }
}

/** Names of all system-seeded skills — useful for delete protection later. */
export function getSystemSkillNames(): string[] {
  return SYSTEM_SKILLS.map((s) => s.name);
}

/** Default content for a system skill (for reset-on-delete). */
export function getSystemSkillDefault(name: string): string | undefined {
  return SYSTEM_SKILLS.find((s) => s.name === name)?.content;
}
