use anyhow::Result;
use std::fs;
use std::path::{Path, PathBuf};

pub fn ensure_directory(path: &Path) -> Result<()> {
    if !path.exists() {
        fs::create_dir_all(path)?;
    }
    Ok(())
}

pub fn write_to_file(content: &str, path: &Path) -> Result<()> {
    // Ensure the parent directory exists
    if let Some(parent) = path.parent() {
        ensure_directory(parent)?;
    }
    fs::write(path, content)?;
    Ok(())
}

pub fn get_model_file_path(project_dir: &Path, language: &str) -> PathBuf {
    let models_dir = project_dir.join("app").join("datamodels");
    match language.to_lowercase().as_str() {
        "python" => models_dir.join("models.py"),
        "typescript" => models_dir.join("model.ts"),
        _ => panic!("Unsupported language"),
    }
}

pub fn get_scripts_dir(project_dir: &Path) -> PathBuf {
    project_dir.join("app").join("scripts")
}

pub fn append_to_file(content: &str, path: &Path) -> Result<()> {
    // Ensure the parent directory exists
    if let Some(parent) = path.parent() {
        ensure_directory(parent)?;
    }

    // If file doesn't exist, create it
    if !path.exists() {
        fs::write(path, content)?;
        return Ok(());
    }

    // Read existing content
    let mut existing_content = fs::read_to_string(path)?;

    // Add two newlines before new content if file is not empty
    if !existing_content.is_empty() && !existing_content.ends_with("\n\n") {
        existing_content.push_str("\n\n");
    }

    // Append new content
    existing_content.push_str(content);

    // Write back to file
    fs::write(path, existing_content)?;
    Ok(())
}
