// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

use std::fmt::Write;

use anki_io::create_dir_all;
use anki_io::write_file_if_changed;
use anyhow::Result;
use itertools::Itertools;

use crate::archives::with_exe;
use crate::input::space_separated;
use crate::Build;

impl Build {
    pub fn render(&self) -> String {
        let mut buf = String::new();

        writeln!(
            &mut buf,
            "# This file is automatically generated by configure.rs. Any edits will be lost.\n"
        )
        .unwrap();

        writeln!(&mut buf, "builddir = {}", self.buildroot.as_str()).unwrap();
        writeln!(
            &mut buf,
            "runner = $builddir/rust/release/{}",
            with_exe("runner")
        )
        .unwrap();
        for (key, value) in &self.variables {
            writeln!(&mut buf, "{key} = {value}").unwrap();
        }
        buf.push('\n');

        for (key, value) in &self.pools {
            writeln!(&mut buf, "pool {key}\n  depth = {value}").unwrap();
        }
        buf.push('\n');

        buf.push_str(&self.output_text);

        for (group, targets) in self.groups.iter().sorted() {
            let group = group.replace(':', "_");
            writeln!(
                &mut buf,
                "build {group}: phony {}",
                space_separated(targets)
            )
            .unwrap();
            buf.push('\n');
        }

        buf.push_str(&self.trailing_text);

        buf
    }

    pub fn write_build_file(&self) -> Result<()> {
        create_dir_all(&self.buildroot)?;
        let path = self.buildroot.join("build.ninja");
        let contents = self.render().into_bytes();
        write_file_if_changed(path, contents)?;
        Ok(())
    }
}
