"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PYTHON_AGENT_CONFIG = void 0;
const framework_config_1 = require("../../lib/framework-config");
const package_manager_detection_1 = require("../../lib/package-manager-detection");
const constants_1 = require("../../lib/constants");
const fast_glob_1 = __importDefault(require("fast-glob"));
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const utils_1 = require("./utils");
// Glob ignores for Python detection. CRITICAL: must include `node_modules`,
// `dist`, and `build` — without them, scanning a Node.js monorepo for
// `**/pyproject.toml` walks every transitive dep's package.json siblings
// and turns a sub-100ms detection into a 6+ second one. See
// commit history on this file for the regression we're fixing.
const IGNORE_PATTERNS = [
    '**/node_modules/**',
    '**/dist/**',
    '**/build/**',
    '**/venv/**',
    '**/.venv/**',
    '**/env/**',
    '**/.env/**',
    '**/__pycache__/**',
];
exports.PYTHON_AGENT_CONFIG = {
    metadata: {
        name: 'Python Language',
        glyph: '🐍',
        glyphColor: '#FFD43B',
        integration: constants_1.Integration.python,
        beta: true,
        docsUrl: 'https://amplitude.com/docs/sdks/analytics/python',
        gatherContext: async (options) => {
            const packageManager = await (0, utils_1.detectPackageManager)(options);
            return { packageManager };
        },
    },
    detection: {
        packageName: 'python',
        packageDisplayName: 'Python',
        usesPackageJson: false,
        getVersion: () => undefined,
        getVersionBucket: utils_1.getPythonVersionBucket,
        minimumVersion: '3.8.0',
        getInstalledVersion: (options) => Promise.resolve((0, utils_1.getPythonVersion)(options)),
        detect: async (options) => {
            const { installDir } = options;
            // Look for Python package management files
            const pythonConfigFiles = await (0, fast_glob_1.default)([
                '**/requirements*.txt',
                '**/pyproject.toml',
                '**/setup.py',
                '**/Pipfile',
            ], {
                cwd: installDir,
                ignore: IGNORE_PATTERNS,
            });
            if (pythonConfigFiles.length === 0) {
                return false;
            }
            // Make sure this isn't Django or Flask (those should be detected first)
            // Check for Django
            const managePyMatches = await (0, fast_glob_1.default)('**/manage.py', {
                cwd: installDir,
                ignore: IGNORE_PATTERNS,
            });
            for (const match of managePyMatches) {
                try {
                    const content = fs.readFileSync(path.join(installDir, match), 'utf-8');
                    if (content.includes('django') ||
                        content.includes('DJANGO_SETTINGS_MODULE')) {
                        return false; // Django detected, use django agent instead
                    }
                }
                catch {
                    continue;
                }
            }
            // Check for Flask
            for (const configFile of pythonConfigFiles) {
                try {
                    const content = fs.readFileSync(path.join(installDir, configFile), 'utf-8');
                    if (/^flask([<>=~!]|$|\s)/im.test(content) ||
                        /["']flask["']/i.test(content)) {
                        return false; // Flask detected, use flask agent instead
                    }
                }
                catch {
                    continue;
                }
            }
            const pyFiles = await (0, fast_glob_1.default)(['**/app.py', '**/wsgi.py', '**/application.py', '**/__init__.py'], {
                cwd: installDir,
                ignore: IGNORE_PATTERNS,
            });
            for (const pyFile of pyFiles) {
                try {
                    const content = fs.readFileSync(path.join(installDir, pyFile), 'utf-8');
                    if (content.includes('from flask import') ||
                        content.includes('import flask') ||
                        /Flask\s*\(/.test(content)) {
                        return false; // Flask detected, use flask agent instead
                    }
                }
                catch {
                    continue;
                }
            }
            // If we have Python config files but it's not Django or Flask, it's a generic Python project
            return true;
        },
        detectPackageManager: package_manager_detection_1.detectPythonPackageManagers,
    },
    environment: {
        uploadToHosting: false,
        getEnvVars: (apiKey, _host) => ({
            AMPLITUDE_API_KEY: apiKey,
        }),
    },
    analytics: {
        getTags: (context) => {
            const packageManagerName = context.packageManager
                ? (0, utils_1.getPackageManagerName)(context.packageManager)
                : 'unknown';
            return {
                packageManager: packageManagerName,
            };
        },
    },
    prompts: {
        packageInstallation: framework_config_1.PYTHON_PACKAGE_INSTALLATION,
        projectTypeDetection: 'This is a generic Python project. Look for requirements.txt, pyproject.toml, setup.py, or Pipfile to confirm.',
        getAdditionalContextLines: (context) => {
            const packageManagerName = context.packageManager
                ? (0, utils_1.getPackageManagerName)(context.packageManager)
                : 'unknown';
            return [
                `Package manager: ${packageManagerName}`,
                `Framework docs ID: python (use amplitude://docs/frameworks/python for documentation)`,
                `Project type: Generic Python application (CLI, script, worker, data pipeline, etc.)`,
            ];
        },
    },
    ui: {
        successMessage: 'Amplitude integration complete',
        estimatedDurationMinutes: 5,
        getOutroChanges: (context) => {
            const packageManagerName = context.packageManager
                ? (0, utils_1.getPackageManagerName)(context.packageManager)
                : 'package manager';
            return [
                `Analyzed your Python project structure`,
                `Installed the Amplitude Python package using ${packageManagerName}`,
                `Created Amplitude initialization using instance-based API (Amplitude class)`,
                `Configured exception autocapture and graceful shutdown`,
                `Added example code for events and user identification (without PII)`,
            ];
        },
        getOutroNextSteps: () => [
            'Use the Amplitude client for all tracking calls',
            'Call amplitude_client.shutdown() on application exit (use atexit.register)',
            'NEVER send PII in event properties (no emails, names, or user content)',
            'Use amplitude_client.track() for events and amplitude_client.identify() for users',
            'Visit your Amplitude dashboard to see incoming events',
        ],
    },
};
