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

export class MarkdownFileWriter {
    public ensureDir(dirPath: string): void {
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }
    }

    public writeMarkdown(filePath: string, content: string): string {
        this.ensureDir(path.dirname(filePath));
        const finalPath = this.getAvailablePath(filePath);
        fs.writeFileSync(finalPath, this.normalize(content), 'utf8');
        return finalPath;
    }

    public appendMarkdown(filePath: string, content: string): void {
        this.ensureDir(path.dirname(filePath));
        fs.appendFileSync(filePath, this.normalize(content), 'utf8');
    }

    private getAvailablePath(filePath: string): string {
        if (!fs.existsSync(filePath)) return filePath;

        const dir = path.dirname(filePath);
        const ext = path.extname(filePath);
        const base = path.basename(filePath, ext);
        let index = 2;

        while (true) {
            const candidate = path.join(dir, `${base}-${index}${ext}`);
            if (!fs.existsSync(candidate)) return candidate;
            index += 1;
        }
    }

    private normalize(content: string): string {
        return content.replace(/\r\n/g, '\n').trimEnd() + '\n';
    }
}
