import path from 'path';
import fs from 'fs-extra';

// The watch folder is in the project root, which is the parent of the 'src' directory.
// process.cwd() in Next.js usually points to the project root (where package.json is).
// If package.json is in 'src', then process.cwd() is 'src'.
// Let's assume the structure:
// /Project
//   /src (Next.js app)
//   /watch

export const WATCH_DIR_NAME = 'watch';
export const SPECTROGRAMS_DIR_NAME = 'spectrograms';

export function getWatchPath(): string {
    if (process.env.WATCH_DIR) {
        return process.env.WATCH_DIR;
    }

    // We assume the app is running from 'src' or the root containing 'src'.
    // If process.cwd() is .../Crossfade/src, then watch is ../watch
    // If process.cwd() is .../Crossfade, then watch is ./watch

    const cwd = process.cwd();
    if (cwd.endsWith('src')) {
        return path.join(cwd, '..', WATCH_DIR_NAME);
    }
    return path.join(cwd, WATCH_DIR_NAME);
}

export function getSpectrogramsPath(): string {
    const cwd = process.cwd();
    if (cwd.endsWith('src')) {
        return path.join(cwd, '..', SPECTROGRAMS_DIR_NAME);
    }
    return path.join(cwd, SPECTROGRAMS_DIR_NAME);
}

export async function ensureWatchDir() {
    const watchPath = getWatchPath();
    await fs.ensureDir(watchPath);
    return watchPath;
}

export async function ensureSpectrogramsDir() {
    const specPath = getSpectrogramsPath();
    await fs.ensureDir(specPath);
    return specPath;
}

export function getOutputDir(): string | null {
    const outputDir = process.env.OUTPUT_DIR;
    if (!outputDir) return null;
    return outputDir;
}
