/**
 * Provider Detector
 *
 * Detects deployment provider from project configuration.
 *
 * @module scanners/deploy/provider-detector
 */
import { readFile, access } from "fs/promises";
import { join } from "path";
import { logger } from "../../logger.js";
/**
 * Provider detection patterns
 */
const PROVIDER_PATTERNS = [
    {
        provider: "vercel",
        files: ["vercel.json", "vercel.ts", ".vercel/project.json"],
        packageIndicators: ["@vercel/node", "@vercel/next", "vercel"],
        envIndicators: ["VERCEL", "VERCEL_URL", "VERCEL_ENV"],
    },
    {
        provider: "aws",
        files: ["serverless.yml", "serverless.yaml", "samconfig.toml", "cdk.json", "amplify.yml"],
        packageIndicators: ["@aws-cdk/core", "aws-cdk-lib", "serverless", "@aws-amplify/cli"],
        envIndicators: ["AWS_REGION", "AWS_LAMBDA_FUNCTION_NAME"],
    },
    {
        provider: "gcp",
        files: ["app.yaml", "cloudbuild.yaml", ".gcloudignore"],
        packageIndicators: ["@google-cloud/functions-framework", "firebase-functions"],
        envIndicators: ["GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GCP_PROJECT"],
    },
    {
        provider: "railway",
        files: ["railway.json", "railway.toml"],
        packageIndicators: [],
        envIndicators: ["RAILWAY_ENVIRONMENT", "RAILWAY_PROJECT_ID"],
    },
    {
        provider: "render",
        files: ["render.yaml"],
        packageIndicators: [],
        envIndicators: ["RENDER", "RENDER_SERVICE_ID"],
    },
    {
        provider: "fly",
        files: ["fly.toml"],
        packageIndicators: [],
        envIndicators: ["FLY_APP_NAME", "FLY_REGION"],
    },
];
/**
 * Detect deployment provider from project
 */
export async function detectProvider(projectPath) {
    const indicators = [];
    let bestMatch;
    let bestConfidence = 0;
    for (const pattern of PROVIDER_PATTERNS) {
        let confidence = 0;
        // Check for provider-specific files
        for (const file of pattern.files) {
            try {
                await access(join(projectPath, file));
                confidence += 40;
                indicators.push(`Found ${file}`);
            }
            catch {
                // File doesn't exist
            }
        }
        // Check package.json for dependencies
        try {
            const packageJsonPath = join(projectPath, "package.json");
            const packageJson = JSON.parse(await readFile(packageJsonPath, "utf-8"));
            const allDeps = {
                ...packageJson.dependencies,
                ...packageJson.devDependencies,
            };
            for (const indicator of pattern.packageIndicators) {
                if (allDeps[indicator]) {
                    confidence += 25;
                    indicators.push(`Found ${indicator} in package.json`);
                }
            }
        }
        catch {
            // No package.json or parse error
        }
        // Check environment variables
        for (const envVar of pattern.envIndicators) {
            if (process.env[envVar]) {
                confidence += 35;
                indicators.push(`Found ${envVar} environment variable`);
            }
        }
        if (confidence > bestConfidence) {
            bestConfidence = confidence;
            bestMatch = pattern;
        }
    }
    if (bestMatch && bestConfidence > 0) {
        // Try to get project ID from config
        let projectId;
        let configPath;
        if (bestMatch.provider === "vercel") {
            try {
                const vercelProject = JSON.parse(await readFile(join(projectPath, ".vercel/project.json"), "utf-8"));
                projectId = vercelProject.projectId;
                configPath = ".vercel/project.json";
            }
            catch {
                // No project.json
            }
        }
        logger.info("deploy.provider_detected", {
            provider: bestMatch.provider,
            confidence: Math.min(bestConfidence, 100),
        });
        return {
            provider: bestMatch.provider,
            confidence: Math.min(bestConfidence, 100),
            indicators,
            projectId,
            configPath,
        };
    }
    return {
        provider: "unknown",
        confidence: 0,
        indicators: ["No deployment provider detected"],
    };
}
/**
 * Get provider-specific deployment URL pattern
 */
export function getDeploymentUrlPattern(provider) {
    switch (provider) {
        case "vercel":
            return /https:\/\/[\w-]+\.vercel\.app/;
        case "railway":
            return /https:\/\/[\w-]+\.railway\.app/;
        case "render":
            return /https:\/\/[\w-]+\.onrender\.com/;
        case "fly":
            return /https:\/\/[\w-]+\.fly\.dev/;
        default:
            return null;
    }
}
/**
 * Check if running in a deployment environment
 */
export function isDeploymentEnvironment() {
    return !!(process.env.VERCEL ||
        process.env.AWS_LAMBDA_FUNCTION_NAME ||
        process.env.GOOGLE_CLOUD_PROJECT ||
        process.env.RAILWAY_ENVIRONMENT ||
        process.env.RENDER ||
        process.env.FLY_APP_NAME);
}
/**
 * Get current environment from provider
 */
export function getCurrentEnvironment(provider) {
    switch (provider) {
        case "vercel":
            return process.env.VERCEL_ENV || "development";
        case "railway":
            return process.env.RAILWAY_ENVIRONMENT || "development";
        case "render":
            return process.env.RENDER ? "production" : "development";
        default:
            return process.env.NODE_ENV || "development";
    }
}
//# sourceMappingURL=provider-detector.js.map