// tools/activate-license.ts — Handler for activate_license MCP tool.
// Activates a license key via Lemon Squeezy API and persists the state locally.
import { hostname, platform, userInfo } from 'node:os';
import { basename } from 'node:path';
import { licenseStore } from '../storage/index.js';
import { activateLicense, computeMachineFingerprint, deactivateLicense, loadLicensePlans, variantToTier, } from '../engine/license-validator.js';
import { invalidateTierCache } from './license-gate.js';
import { t, ti } from '../i18n/index.js';
function buildInstanceName() {
    const host = hostname();
    const user = userInfo().username;
    const os = platform();
    const project = basename(process.cwd());
    return `planu-${host} · ${user}@${os} · ${project}`;
}
export async function handleActivateLicense(args) {
    const { licenseKey, instanceName } = args;
    if (!licenseKey || licenseKey.trim().length === 0) {
        return {
            content: [{ type: 'text', text: t('tools.activate_license.keyRequired') }],
            isError: true,
        };
    }
    const name = instanceName ?? buildInstanceName();
    try {
        const response = await activateLicense(licenseKey.trim(), name);
        if (!response.activated) {
            return {
                content: [
                    {
                        type: 'text',
                        text: ti('tools.activate_license.activationFailed', {
                            error: response.error ?? 'Unknown error',
                        }),
                    },
                ],
                isError: true,
            };
        }
        const tier = variantToTier(response.meta.variant_name);
        const now = new Date().toISOString();
        const state = {
            licenseKey: response.license_key.key,
            instanceId: response.instance.id,
            tier,
            activatedAt: now,
            lastValidatedAt: now,
            variantName: response.meta.variant_name,
            customerName: response.meta.customer_name,
            customerEmail: response.meta.customer_email,
            machineFingerprint: computeMachineFingerprint(),
            activationLimit: response.license_key.activation_limit,
            activationUsage: response.license_key.activation_usage,
        };
        await licenseStore.saveLicenseState(state);
        invalidateTierCache();
        const tierLabel = tier.charAt(0).toUpperCase() + tier.slice(1);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `✅ ${t('tools.activate_license.activatedSuccess')}`,
                        '',
                        ti('tools.activate_license.plan', { tier: tierLabel }),
                        ti('tools.activate_license.customer', { name: response.meta.customer_name }),
                        ti('tools.activate_license.instance', { name }),
                        '',
                        tier === 'pro'
                            ? t('tools.activate_license.proAccess')
                            : ti('tools.activate_license.tierAccess', { tier }),
                    ].join('\n'),
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        ti('tools.activate_license.activationFailed', { error: message }),
                        '',
                        t('tools.activate_license.commonCauses'),
                        `• ${t('tools.activate_license.causeInvalidKey')}`,
                        `• ${t('tools.activate_license.causeAlreadyActivated')}`,
                        `• ${t('tools.activate_license.causeNetwork')}`,
                    ].join('\n'),
                },
            ],
            isError: true,
        };
    }
}
export async function handleDeactivateLicense(args) {
    if (!args.confirm) {
        return {
            content: [{ type: 'text', text: t('tools.activate_license.deactivationCancelled') }],
        };
    }
    const state = await licenseStore.getLicenseState();
    if (!state) {
        return {
            content: [{ type: 'text', text: t('tools.activate_license.noActiveLicense') }],
        };
    }
    try {
        await deactivateLicense(state.licenseKey, state.instanceId);
    }
    catch {
        // Even if remote deactivation fails, we clear local state
    }
    await licenseStore.deleteLicenseState();
    invalidateTierCache();
    return {
        content: [
            {
                type: 'text',
                text: [
                    `✅ ${t('tools.activate_license.deactivatedSuccess')}`,
                    ti('tools.activate_license.deactivatedFreePlan', {
                        count: String(loadLicensePlans().freeTools.length),
                    }),
                    t('tools.activate_license.keyReusable'),
                ].join('\n'),
            },
        ],
    };
}
//# sourceMappingURL=activate-license.js.map