import * as fs from 'fs';
import * as path from 'path';
import dotenv from 'dotenv';

// Load environment variables from .env file
dotenv.config();

export interface Config {
    github: {
        token: string;
        repository: string;
        baseBranch: string;
    };
    jira: {
        token: string;
        baseUrl: string;
        projectKey: string;
    };
}

function validateGitHubConfig(config: Config['github']): string[] {
    const errors: string[] = [];
    
    // Validate GitHub token format (should be a 40-character hex string)
    if (!/^[0-9a-f]{40}$/i.test(config.token)) {
        errors.push('GITHUB_TOKEN must be a valid 40-character GitHub token');
    }

    // Validate repository format (username/repo)
    if (!/^[a-zA-Z0-9-]+\/[a-zA-Z0-9-_.]+$/.test(config.repository)) {
        errors.push('GITHUB_REPOSITORY must be in the format "username/repository"');
    }

    // Validate base branch (should be a valid git branch name)
    if (!/^[a-zA-Z0-9-_.]+$/.test(config.baseBranch)) {
        errors.push('GITHUB_BASE_BRANCH must be a valid git branch name');
    }

    return errors;
}

function validateJiraConfig(config: Config['jira']): string[] {
    const errors: string[] = [];
    
    // Validate Jira token (should be a valid API token)
    if (!config.token || config.token.length < 10) {
        errors.push('JIRA_TOKEN must be a valid Jira API token');
    }

    // Validate Jira base URL
    try {
        const url = new URL(config.baseUrl);
        if (!url.protocol.startsWith('http')) {
            errors.push('JIRA_BASE_URL must be a valid HTTP(S) URL');
        }
    } catch {
        errors.push('JIRA_BASE_URL must be a valid URL');
    }

    // Validate project key (should be 2-10 characters, uppercase)
    if (!/^[A-Z]{2,10}$/.test(config.projectKey)) {
        errors.push('JIRA_PROJECT_KEY must be 2-10 uppercase letters');
    }

    return errors;
}

export function loadConfig(): Config {
    // First try to load from .env file
    const config: Config = {
        github: {
            token: process.env.GITHUB_TOKEN || '',
            repository: process.env.GITHUB_REPOSITORY || '',
            baseBranch: process.env.GITHUB_BASE_BRANCH || 'main'
        },
        jira: {
            token: process.env.JIRA_TOKEN || '',
            baseUrl: process.env.JIRA_BASE_URL || '',
            projectKey: process.env.JIRA_PROJECT_KEY || ''
        }
    };

    // Validate required configuration
    const missingConfig = [];
    if (!config.github.token) missingConfig.push('GITHUB_TOKEN');
    if (!config.github.repository) missingConfig.push('GITHUB_REPOSITORY');
    if (!config.jira.token) missingConfig.push('JIRA_TOKEN');
    if (!config.jira.baseUrl) missingConfig.push('JIRA_BASE_URL');
    if (!config.jira.projectKey) missingConfig.push('JIRA_PROJECT_KEY');

    if (missingConfig.length > 0) {
        throw new Error(`Missing required configuration: ${missingConfig.join(', ')}. Please set these in your .env file.`);
    }

    // Validate configuration values
    const githubErrors = validateGitHubConfig(config.github);
    const jiraErrors = validateJiraConfig(config.jira);

    const validationErrors = [...githubErrors, ...jiraErrors];
    if (validationErrors.length > 0) {
        throw new Error(`Configuration validation failed:\n${validationErrors.join('\n')}`);
    }

    return config;
} 