//! CSV output formatting

#![allow(dead_code)]
#![allow(unused_imports)]

use crate::cli::output::Tabular;
use crate::error::Result;
use serde::Serialize;
use std::io::{self, Write};

/// CSV output formatter
pub struct CsvOutput {
    writer: csv::Writer<Vec<u8>>,
}

impl CsvOutput {
    pub fn new() -> Self {
        Self {
            writer: csv::Writer::from_writer(Vec::new()),
        }
    }

    /// Print a single value as CSV
    pub fn print<T: Serialize + Tabular>(&self, value: &T) -> Result<()> {
        let mut wtr = csv::Writer::from_writer(io::stdout());
        wtr.serialize(value)?;
        wtr.flush()?;
        Ok(())
    }

    /// Print multiple values as CSV with headers
    pub fn print_rows<T: Serialize + Tabular>(&self, values: &[T]) -> Result<()> {
        let mut wtr = csv::Writer::from_writer(io::stdout());

        // Write header
        wtr.write_record(&T::headers())?;

        // Write rows
        for value in values {
            wtr.write_record(&value.row())?;
        }

        wtr.flush()?;
        Ok(())
    }

    /// Print using serde serialization
    pub fn print_serde<T: Serialize>(&self, values: &[T]) -> Result<()> {
        let mut wtr = csv::Writer::from_writer(io::stdout());
        for value in values {
            wtr.serialize(value)?;
        }
        wtr.flush()?;
        Ok(())
    }
}

impl Default for CsvOutput {
    fn default() -> Self {
        Self::new()
    }
}
