// 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 } from 'node:os';
import { licenseStore } from '../storage/index.js';
import { activateLicense, computeMachineFingerprint, deactivateLicense, loadLicensePlans, variantToTier, } from '../engine/license-validator.js';
import { invalidateTierCache } from './license-gate.js';
export async function handleActivateLicense(args) {
    const { licenseKey, instanceName } = args;
    if (!licenseKey || licenseKey.trim().length === 0) {
        return {
            content: [{ type: 'text', text: 'Error: licenseKey is required.' }],
            isError: true,
        };
    }
    const name = instanceName ?? `planu-${hostname()}`;
    try {
        const response = await activateLicense(licenseKey.trim(), name);
        if (!response.activated) {
            return {
                content: [
                    { type: 'text', text: `License activation failed: ${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();
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `✅ License activated successfully!`,
                        '',
                        `Plan: ${tier.charAt(0).toUpperCase() + tier.slice(1)}`,
                        `Customer: ${response.meta.customer_name}`,
                        `Instance: ${name}`,
                        '',
                        tier === 'pro'
                            ? 'You now have access to all 65 Planu tools and increased limits.'
                            : `You now have ${tier} access with all tools and unlimited projects/specs.`,
                    ].join('\n'),
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `License activation failed: ${message}`,
                        '',
                        'Common causes:',
                        '• Invalid license key — check for typos',
                        '• License already activated on another machine — deactivate first',
                        '• Network issue — check your internet connection',
                    ].join('\n'),
                },
            ],
            isError: true,
        };
    }
}
export async function handleDeactivateLicense(args) {
    if (!args.confirm) {
        return {
            content: [{ type: 'text', text: 'Deactivation cancelled. Set confirm: true to proceed.' }],
        };
    }
    const state = await licenseStore.getLicenseState();
    if (!state) {
        return {
            content: [{ type: 'text', text: 'No active license found. You are on the Free plan.' }],
        };
    }
    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: [
                    '✅ License deactivated successfully.',
                    `You are now on the Free plan (${String(loadLicensePlans().freeTools.length)} tools, 2 projects, 5 active specs).`,
                    'Your license key can be activated on another machine.',
                ].join('\n'),
            },
        ],
    };
}
//# sourceMappingURL=activate-license.js.map