use std::fmt::Write;
use std::path::Path;

use scythe_backend::manifest::{BackendManifest, load_manifest};
use scythe_backend::naming::{
    enum_type_name, enum_variant_name, fn_name, row_struct_name, to_pascal_case,
};

use scythe_core::analyzer::{AnalyzedQuery, CompositeInfo, EnumInfo};
use scythe_core::errors::{ErrorCode, ScytheError};
use scythe_core::parser::QueryCommand;

use crate::backend_trait::{CodegenBackend, ResolvedColumn, ResolvedParam};

const DEFAULT_MANIFEST_TOML: &str = include_str!("../../manifests/ruby-pg.toml");

pub struct RubyPgBackend {
    manifest: BackendManifest,
}

impl RubyPgBackend {
    pub fn new() -> Result<Self, ScytheError> {
        let manifest_path = Path::new("backends/ruby-pg/manifest.toml");
        let manifest = if manifest_path.exists() {
            load_manifest(manifest_path)
                .map_err(|e| ScytheError::new(ErrorCode::InternalError, format!("manifest: {e}")))?
        } else {
            toml::from_str(DEFAULT_MANIFEST_TOML)
                .map_err(|e| ScytheError::new(ErrorCode::InternalError, format!("manifest: {e}")))?
        };
        Ok(Self { manifest })
    }

    pub fn manifest(&self) -> &BackendManifest {
        &self.manifest
    }
}

/// Map a neutral type to a Ruby type coercion method.
fn ruby_coercion(neutral_type: &str) -> &'static str {
    match neutral_type {
        "int16" | "int32" | "int64" => ".to_i",
        "float32" | "float64" => ".to_f",
        "bool" => " == \"t\"",
        _ => "",
    }
}

impl CodegenBackend for RubyPgBackend {
    fn name(&self) -> &str {
        "ruby-pg"
    }

    fn file_header(&self) -> String {
        "# frozen_string_literal: true\n\n# Auto-generated by scythe. Do not edit.\n".to_string()
    }

    fn generate_row_struct(
        &self,
        query_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let struct_name = row_struct_name(query_name, &self.manifest.naming);
        let fields = columns
            .iter()
            .map(|c| format!(":{}", c.field_name))
            .collect::<Vec<_>>()
            .join(", ");
        let mut out = String::new();
        let _ = writeln!(out, "{} = Data.define({})", struct_name, fields);
        Ok(out)
    }

    fn generate_model_struct(
        &self,
        table_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let name = to_pascal_case(table_name);
        self.generate_row_struct(&name, columns)
    }

    fn generate_query_fn(
        &self,
        analyzed: &AnalyzedQuery,
        struct_name: &str,
        columns: &[ResolvedColumn],
        params: &[ResolvedParam],
    ) -> Result<String, ScytheError> {
        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let sql = super::clean_sql(&analyzed.sql);
        let mut out = String::new();

        // Parameter list
        let param_list = params
            .iter()
            .map(|p| p.field_name.clone())
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        let _ = writeln!(out, "def self.{}(conn{}{})", func_name, sep, param_list);

        // Build exec_params call
        let param_array = if params.is_empty() {
            "[]".to_string()
        } else {
            format!(
                "[{}]",
                params
                    .iter()
                    .map(|p| p.field_name.clone())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };

        match &analyzed.command {
            QueryCommand::One => {
                let _ = writeln!(
                    out,
                    "  result = conn.exec_params(\"{}\", {})",
                    sql, param_array
                );
                let _ = writeln!(out, "  return nil if result.ntuples.zero?");
                let _ = writeln!(out, "  row = result[0]");

                // Build struct constructor
                let fields = columns
                    .iter()
                    .map(|c| {
                        let coercion = ruby_coercion(&c.neutral_type);
                        if c.nullable {
                            format!(
                                "{}: row[\"{}\"]&.then {{ |v| v{} }}",
                                c.field_name, c.name, coercion
                            )
                        } else {
                            format!("{}: row[\"{}\"]{}", c.field_name, c.name, coercion)
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "  {}.new({})", struct_name, fields);
            }
            QueryCommand::Many | QueryCommand::Batch => {
                let _ = writeln!(
                    out,
                    "  result = conn.exec_params(\"{}\", {})",
                    sql, param_array
                );
                let _ = writeln!(out, "  result.map do |row|");
                let fields = columns
                    .iter()
                    .map(|c| {
                        let coercion = ruby_coercion(&c.neutral_type);
                        if c.nullable {
                            format!(
                                "{}: row[\"{}\"]&.then {{ |v| v{} }}",
                                c.field_name, c.name, coercion
                            )
                        } else {
                            format!("{}: row[\"{}\"]{}", c.field_name, c.name, coercion)
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "    {}.new({})", struct_name, fields);
                let _ = writeln!(out, "  end");
            }
            QueryCommand::Exec => {
                let _ = writeln!(out, "  conn.exec_params(\"{}\", {})", sql, param_array);
                let _ = writeln!(out, "  nil");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(
                    out,
                    "  result = conn.exec_params(\"{}\", {})",
                    sql, param_array
                );
                let _ = writeln!(out, "  result.cmd_tuples.to_i");
            }
        }

        let _ = write!(out, "end");
        Ok(out)
    }

    fn generate_enum_def(&self, enum_info: &EnumInfo) -> Result<String, ScytheError> {
        let type_name = enum_type_name(&enum_info.sql_name, &self.manifest.naming);
        let mut out = String::new();
        let _ = writeln!(out, "module {}", type_name);
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "  {} = \"{}\"", variant, value);
        }
        // ALL constant
        let all_values = enum_info
            .values
            .iter()
            .map(|v| enum_variant_name(v, &self.manifest.naming))
            .collect::<Vec<_>>()
            .join(", ");
        let _ = writeln!(out, "  ALL = [{}].freeze", all_values);
        let _ = write!(out, "end");
        Ok(out)
    }

    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        let name = to_pascal_case(&composite.sql_name);
        let mut out = String::new();
        if composite.fields.is_empty() {
            let _ = writeln!(out, "{} = Data.define()", name);
        } else {
            let fields = composite
                .fields
                .iter()
                .map(|f| format!(":{}", f.name))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(out, "{} = Data.define({})", name, fields);
        }
        Ok(out)
    }
}
