import { getSentryConfig, saveSentryConfig } from '../storage/sentry-store.js';
import { fetchSentryIssues, fetchSentryIssue, fetchIssueStacktrace, } from '../engine/sentry/sentry-client.js';
import { mapIssueToSpecTitle, mapIssueToDescription, mapIssueToAcceptanceCriteria, mapIssuePriority, } from '../engine/sentry/sentry-spec-mapper.js';
import { handleCreateSpec } from './create-spec.js';
// ---------------------------------------------------------------------------
// configure_sentry
// ---------------------------------------------------------------------------
export async function handleConfigureSentry(input) {
    const now = new Date().toISOString();
    const config = {
        dsn: input.dsn,
        authToken: input.authToken,
        organizationSlug: input.organizationSlug,
        projectSlug: input.projectSlug,
        configuredAt: now,
    };
    await saveSentryConfig(input.projectPath, config);
    const lines = [
        'Sentry configured successfully.',
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Organization | ${input.organizationSlug} |`,
        `| Project | ${input.projectSlug} |`,
        `| DSN | ${maskDsn(input.dsn)} |`,
        `| Configured at | ${now} |`,
    ];
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
// ---------------------------------------------------------------------------
// sentry_status
// ---------------------------------------------------------------------------
export async function handleSentryStatus(input) {
    const config = await getSentryConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Sentry no está conectado. Usa start_oauth_flow con integration="sentry" para ver las instrucciones.',
                },
            ],
        };
    }
    const lines = [
        '**Sentry Configuration**',
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Organization | ${config.organizationSlug} |`,
        `| Project | ${config.projectSlug} |`,
        `| DSN | ${maskDsn(config.dsn)} |`,
        `| Configured at | ${config.configuredAt} |`,
    ];
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
// ---------------------------------------------------------------------------
// sentry_errors_report
// ---------------------------------------------------------------------------
export async function handleSentryErrorsReport(input) {
    const config = await getSentryConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Sentry no está conectado. Usa start_oauth_flow con integration="sentry" para ver las instrucciones.',
                },
            ],
            isError: true,
        };
    }
    const limit = input.limit ?? 10;
    const unresolved = input.unresolved ?? true;
    const issues = await fetchSentryIssues(config, limit, input.level, unresolved);
    if (issues.length === 0) {
        return {
            content: [{ type: 'text', text: 'No issues found matching the criteria.' }],
        };
    }
    const lines = [
        `**Sentry Issues** (${issues.length} found)`,
        '',
        '| ID | Level | Title | Events | Users | Last Seen |',
        '|----|-------|-------|--------|-------|-----------|',
    ];
    for (const issue of issues) {
        const title = issue.title.length > 50 ? `${issue.title.slice(0, 50)}...` : issue.title;
        const lastSeen = issue.lastSeen.slice(0, 10);
        lines.push(`| ${issue.id} | ${issue.level} | ${title} | ${issue.count} | ${issue.userCount} | ${lastSeen} |`);
    }
    lines.push('');
    lines.push('Use `sentry_error_to_spec` with an issue ID to create a bugfix spec.');
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
// ---------------------------------------------------------------------------
// sentry_error_to_spec
// ---------------------------------------------------------------------------
export async function handleSentryErrorToSpec(input) {
    const config = await getSentryConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Sentry no está conectado. Usa start_oauth_flow con integration="sentry" para ver las instrucciones.',
                },
            ],
            isError: true,
        };
    }
    const issue = await fetchSentryIssue(config, input.issueId);
    const stacktrace = await fetchIssueStacktrace(config, input.issueId);
    const title = mapIssueToSpecTitle(issue);
    const criteria = mapIssueToAcceptanceCriteria(issue);
    const priority = mapIssuePriority(issue, input.priority);
    const criteriaSection = criteria.map((c) => `- [ ] ${c}`).join('\n');
    const description = mapIssueToDescription(issue, stacktrace) + '\n\n## Acceptance Criteria\n\n' + criteriaSection;
    const createResult = await handleCreateSpec({
        title,
        description,
        projectPath: input.projectPath,
        type: 'bugfix',
        scope: 'feature',
        target: 'fullstack',
        tags: ['sentry', `sentry-issue:${issue.id}`, `priority:${priority}`],
    });
    if (createResult.isError === true) {
        return createResult;
    }
    // Extract spec ID from result text
    const firstContent = createResult.content[0];
    const resultText = firstContent?.type === 'text' ? firstContent.text : '';
    const specIdMatch = /SPEC-\d+/.exec(resultText);
    const specId = specIdMatch?.[0] ?? 'SPEC-???';
    const now = new Date().toISOString();
    const result = {
        specId,
        specTitle: title,
        issueId: issue.id,
        createdAt: now,
    };
    const summary = [
        `Spec created from Sentry issue ${issue.id}.`,
        '',
        `| Field | Value |`,
        `|-------|-------|`,
        `| Spec ID | ${result.specId} |`,
        `| Title | ${result.specTitle} |`,
        `| Sentry Issue | ${result.issueId} |`,
        `| Priority | ${priority} |`,
        `| Created at | ${result.createdAt} |`,
    ];
    return { content: [{ type: 'text', text: summary.join('\n') }] };
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
function maskDsn(dsn) {
    try {
        const url = new URL(dsn);
        const host = url.hostname;
        return `${url.protocol}//***(masked)***@${host}${url.pathname}`;
    }
    catch {
        return '***(masked)***';
    }
}
//# sourceMappingURL=sentry-handler.js.map