import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import log from 'electron-log';

const NPMRC_PATH = path.join(os.homedir(), '.npmrc');
const INST_REGISTRY_LINE = '@inst:registry=https://instructure.jfrog.io/';
const AUTH_TOKEN_PREFIX = '//instructure.jfrog.io/:_authToken=';

export interface NpmrcStatus {
  configured: boolean;
  npmrcExists: boolean;
  token?: string;
}

export interface NpmrcSetupOptions {
  token: string;
}

export interface InstallResult {
  success: boolean;
  message: string;
}

/**
 * Check the current ~/.npmrc configuration status for @inst registry
 */
export async function checkNpmrcStatus(): Promise<NpmrcStatus> {
  try {
    if (!fs.existsSync(NPMRC_PATH)) {
      return { configured: false, npmrcExists: false };
    }

    const content = fs.readFileSync(NPMRC_PATH, 'utf-8');
    const lines = content.split('\n');

    const hasRegistry = lines.some(line => line.trim() === INST_REGISTRY_LINE);
    const authTokenLine = lines.find(line => line.startsWith(AUTH_TOKEN_PREFIX));
    const token = authTokenLine ? authTokenLine.slice(AUTH_TOKEN_PREFIX.length).trim() : undefined;
    const configured = hasRegistry && !!token;

    return {
      configured,
      npmrcExists: true,
      token: token || undefined
    };
  } catch (error: any) {
    log.error('Error checking .npmrc status:', error);
    return { configured: false, npmrcExists: false };
  }
}

/**
 * Write ~/.npmrc with @inst registry and auth token configuration
 */
export async function setupNpmrc(options: NpmrcSetupOptions): Promise<InstallResult> {
  try {
    if (!options.token || !options.token.trim()) {
      return { success: false, message: 'Auth token is required' };
    }

    const content = `${INST_REGISTRY_LINE}\n${AUTH_TOKEN_PREFIX}${options.token.trim()}\n`;
    fs.writeFileSync(NPMRC_PATH, content, { encoding: 'utf-8', mode: 0o600 });

    log.info('pnpm .npmrc configuration saved successfully');
    return { success: true, message: 'pnpm configuration saved to ~/.npmrc' };
  } catch (error: any) {
    log.error('Failed to write .npmrc:', error);
    return { success: false, message: `Failed to save configuration: ${error.message}` };
  }
}
