/**
 * Environment File Generator
 *
 * Generates minimal .env files containing ONLY secrets (tokens).
 * All configuration is stored in config.json.
 *
 * gh CLI is the recommended authentication method.
 * GITHUB_TOKEN in .env is only needed when gh CLI is not available.
 *
 * @module env-file-generator
 */
import * as fs from '../utils/fs-native.js';
import path from 'path';
/**
 * Generate .env file with GitHub token (only when gh CLI not available)
 *
 * @param projectRoot - Project root directory
 * @param config - Environment configuration
 */
export async function generateEnvFile(projectRoot, config) {
    const envPath = path.join(projectRoot, '.env');
    const envExamplePath = path.join(projectRoot, '.env.example');
    // Build .env content
    const content = buildEnvContent(config);
    const exampleContent = buildEnvExampleContent();
    // Write .env file
    await fs.writeFile(envPath, content, 'utf-8');
    // Set secure permissions (owner read/write only)
    if (process.platform !== 'win32') {
        await fs.chmod(envPath, 0o600);
    }
    // Write .env.example
    await fs.writeFile(envExamplePath, exampleContent, 'utf-8');
    // Update .gitignore
    await updateGitignore(projectRoot);
}
/**
 * Build .env file content (secrets only)
 *
 * @param config - Environment configuration
 * @returns .env content
 */
function buildEnvContent(config) {
    const lines = [];
    lines.push('# GitHub Token (Auto-generated by SpecWeave)');
    lines.push(`# Created: ${new Date().toISOString()}`);
    lines.push('#');
    lines.push('# NOTE: gh CLI authentication is recommended over tokens.');
    lines.push('# Run: gh auth login');
    lines.push('# This file is only needed if gh CLI is not available.');
    lines.push('');
    // GitHub token - the ONLY secret
    if (config.githubToken) {
        lines.push(`GITHUB_TOKEN=${config.githubToken}`);
    }
    else {
        lines.push('GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx');
    }
    lines.push('');
    lines.push('# All other configuration is in .specweave/config.json');
    return lines.join('\n') + '\n';
}
/**
 * Build .env.example file content
 *
 * @returns .env.example content
 */
function buildEnvExampleContent() {
    const lines = [];
    lines.push('# GitHub Configuration');
    lines.push('#');
    lines.push('# RECOMMENDED: Use gh CLI instead of tokens');
    lines.push('#   gh auth login');
    lines.push('#');
    lines.push('# Only use this file if gh CLI is not available.');
    lines.push('# Copy to .env and fill in your token.');
    lines.push('');
    lines.push('# GitHub Personal Access Token');
    lines.push('# Get from: https://github.com/settings/tokens');
    lines.push('# Scopes: repo, read:org');
    lines.push('GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx');
    lines.push('');
    lines.push('# All other configuration is in .specweave/config.json');
    return lines.join('\n') + '\n';
}
/**
 * Update .gitignore to exclude .env files
 *
 * @param projectRoot - Project root directory
 */
async function updateGitignore(projectRoot) {
    const gitignorePath = path.join(projectRoot, '.gitignore');
    let content = '';
    if (await fs.pathExists(gitignorePath)) {
        content = await fs.readFile(gitignorePath, 'utf-8');
    }
    // Check if .env patterns already exist
    const hasEnvPattern = /^\.env$/m.test(content);
    const hasEnvLocalPattern = /^\.env\.local$/m.test(content);
    if (!hasEnvPattern || !hasEnvLocalPattern) {
        const lines = content.split('\n');
        // Add SpecWeave section if not exists
        if (!content.includes('# SpecWeave - Environment variables')) {
            lines.push('');
            lines.push('# SpecWeave - Environment variables (contains secrets!)');
            if (!hasEnvPattern) {
                lines.push('.env');
            }
            if (!hasEnvLocalPattern) {
                lines.push('.env.local');
            }
        }
        await fs.writeFile(gitignorePath, lines.join('\n') + '\n', 'utf-8');
    }
}
/**
 * Check if .env file exists
 *
 * @param projectRoot - Project root directory
 * @returns True if .env exists
 */
export async function envFileExists(projectRoot) {
    const envPath = path.join(projectRoot, '.env');
    return fs.pathExists(envPath);
}
/**
 * Load GitHub token from .env file
 *
 * @param projectRoot - Project root directory
 * @returns GitHub token or null
 */
export async function loadEnvConfig(projectRoot) {
    const envPath = path.join(projectRoot, '.env');
    if (!await fs.pathExists(envPath)) {
        return null;
    }
    const content = await fs.readFile(envPath, 'utf-8');
    const lines = content.split('\n');
    const config = {};
    for (const line of lines) {
        const trimmed = line.trim();
        if (trimmed.startsWith('#') || !trimmed) {
            continue;
        }
        const eqIndex = trimmed.indexOf('=');
        if (eqIndex === -1)
            continue;
        const key = trimmed.slice(0, eqIndex).trim();
        const value = trimmed.slice(eqIndex + 1).trim();
        // CRITICAL FIX (2025-11-26): Check both GITHUB_TOKEN and GH_TOKEN
        // Init flow saves as GH_TOKEN, but some code looks for GITHUB_TOKEN
        // Priority: GITHUB_TOKEN > GH_TOKEN (for backwards compatibility)
        if (key === 'GITHUB_TOKEN') {
            config.githubToken = value;
        }
        else if (key === 'GH_TOKEN' && !config.githubToken) {
            // Only use GH_TOKEN if GITHUB_TOKEN not already set
            config.githubToken = value;
        }
    }
    return config;
}
//# sourceMappingURL=env-file-generator.js.map