/**
 * Rule: plugin-version-required
 *
 * Validates that plugin version is present and non-empty
 *
 * The plugin version is a recommended field used for dependency management
 * and marketplace distribution. It should not be empty or whitespace-only.
 */

import { Rule, RuleContext } from '../../types/rule';
import { safeParseJSON } from '../../utils/formats/json';
import { hasProperty, isString } from '../../utils/type-guards';

export const rule: Rule = {
  meta: {
    id: 'plugin-version-required',
    name: 'Plugin Version Required',
    description: 'Plugin version is recommended and should not be empty',
    category: 'Plugin',
    severity: 'warn',
    fixable: false,
    deprecated: false,
    since: '0.2.0',
    docUrl: 'https://claudelint.com/rules/plugin/plugin-version-required',
    docs: {
      recommended: true,
      summary: 'Warns when plugin.json is missing a version field.',
      rationale:
        'A missing version prevents update detection and complicates marketplace distribution.',
      details:
        'This rule checks that the plugin.json file has a version property that is a non-empty string. ' +
        'The version is used for dependency management and marketplace distribution. While only `name` is ' +
        'strictly required by Claude Code, including a version is strongly recommended for version tracking ' +
        'and update detection.',
      examples: {
        incorrect: [
          {
            description: 'Plugin with missing version',
            code: '{\n  "name": "my-plugin",\n  "description": "A useful plugin"\n}',
            language: 'json',
          },
          {
            description: 'Plugin with empty version',
            code: '{\n  "name": "my-plugin",\n  "version": ""\n}',
            language: 'json',
          },
        ],
        correct: [
          {
            description: 'Plugin with a valid version',
            code: '{\n  "name": "my-plugin",\n  "version": "1.0.0"\n}',
            language: 'json',
          },
        ],
      },
      howToFix:
        'Add a version field to plugin.json with a non-empty string value following semver ' +
        'format (e.g., "1.0.0"). While optional per the spec, it is strongly recommended.',
      relatedRules: ['plugin-invalid-marketplace-manifest'],
    },
  },
  validate: (context: RuleContext) => {
    const { filePath, fileContent } = context;

    // Only validate plugin.json files
    if (!filePath.endsWith('plugin.json')) {
      return;
    }

    const plugin = safeParseJSON(fileContent);
    if (!plugin) {
      return; // Invalid JSON handled by schema validation
    }

    // Check if version is missing or empty
    if (
      !hasProperty(plugin, 'version') ||
      !isString(plugin.version) ||
      plugin.version.trim().length === 0
    ) {
      context.report({
        message: 'Plugin version is recommended but missing or empty',
      });
    }
  },
};
