import { resolve } from 'node:path';
import { INSPECT_TOOL_SCHEMA } from './schema.js';
import { appendSchemaFingerprint } from '../shared/schema-fingerprint.js';
import { VALID_MODES, JSON_OUTPUT_INDENT } from './shared.js';
import { executeInspectMode } from './executor.js';
export class InspectTool {
    featureFlags;
    projectRoot;
    constructor(featureFlags, projectRoot = null) {
        this.featureFlags = featureFlags;
        this.projectRoot = projectRoot;
    }
    definition = {
        name: 'inspect',
        description: 'Inspect and analyze a project or file. Modes: project (structure), api (routes),'
            + ' api_spec (generate OpenAPI 3.0 spec), api_validate (compare spec to code),'
            + ' api_sync (detect frontend/backend drift),'
            + ' database (schema), components (React), layout (CSS/Tailwind),'
            + ' accessibility (a11y issues), scaffold (module skeleton generator).',
        parameters: INSPECT_TOOL_SCHEMA,
        sideEffects: ['read_fs'],
        concurrency: 'parallel',
        supportsProgress: true,
    };
    _withFingerprint(output, mode, indent) {
        try {
            const parsed = JSON.parse(output);
            if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
                const fingerprinted = appendSchemaFingerprint(parsed, 'inspect', mode, {
                    featureFlags: this.featureFlags,
                });
                return JSON.stringify(fingerprinted, null, indent || 0);
            }
        }
        catch {
            // ignore non-JSON output
        }
        return output;
    }
    async execute(args) {
        if (!args.mode || typeof args.mode !== 'string') {
            return { success: false, error: 'mode is required' };
        }
        const input = args;
        if (!VALID_MODES.includes(input.mode)) {
            return { success: false, error: `Invalid mode: ${input.mode}. Valid modes: ${VALID_MODES.join(', ')}` };
        }
        const explicitRoot = (typeof input.projectRoot === 'string' && input.projectRoot.trim().length > 0)
            ? input.projectRoot
            : this.projectRoot;
        if (!explicitRoot) {
            return { success: false, error: 'projectRoot is required' };
        }
        const projectRoot = resolve(explicitRoot);
        const format = input.output?.format ?? 'detailed';
        const rawResult = await executeInspectMode(input, projectRoot, format);
        return this._fingerprintResult(rawResult, input.mode, format);
    }
    _fingerprintResult(result, mode, format) {
        if (result.success && result.output !== undefined) {
            return { ...result, output: this._withFingerprint(result.output, mode, format === 'json' ? JSON_OUTPUT_INDENT : 0) };
        }
        return result;
    }
}
