use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{
    enum_type_name, enum_variant_name, fn_name, row_struct_name, to_pascal_case,
};
use std::fmt::Write;

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

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

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

pub struct RubyMysql2Backend {
    manifest: BackendManifest,
}

impl RubyMysql2Backend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        match engine {
            "mysql" | "mariadb" => {}
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InternalError,
                    format!("ruby-mysql2 only supports MySQL, got engine '{}'", engine),
                ));
            }
        }
        let manifest = super::load_or_default_manifest(
            "backends/ruby-mysql2/manifest.toml",
            DEFAULT_MANIFEST_TOML,
        )?;
        Ok(Self { manifest })
    }
}

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

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

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

    fn supported_engines(&self) -> &[&str] {
        &["mysql", "mariadb"]
    }

    fn generate_rbs_file(&self, context: &RbsGenerationContext) -> Option<String> {
        Some(super::ruby_rbs::generate_rbs_content(
            context,
            "Mysql2::Client",
        ))
    }

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

    fn file_footer(&self) -> String {
        "end".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_with_optional(
            &analyzed.sql,
            &analyzed.optional_params,
            &analyzed.params,
        );
        let mut out = String::new();

        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.{}(client{}{})", func_name, sep, param_list);

        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 | QueryCommand::Opt => {
                let _ = writeln!(out, "    stmt = client.prepare(\"{}\")", sql);
                let _ = writeln!(
                    out,
                    "    results = stmt.execute({})",
                    param_array.trim_start_matches('[').trim_end_matches(']')
                );
                let _ = writeln!(out, "    row = results.first");
                let _ = writeln!(out, "    return nil if row.nil?");

                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::Batch => {
                let batch_fn_name = format!("{}_batch", func_name);
                let _ = writeln!(out, "  def self.{}(client, items)", batch_fn_name);
                let _ = writeln!(out, "    stmt = client.prepare(\"{}\")", sql);
                let _ = writeln!(out, "    items.each do |item|");
                if params.len() > 1 {
                    let _ = writeln!(out, "      stmt.execute(*item)");
                } else if params.len() == 1 {
                    let _ = writeln!(out, "      stmt.execute(item)");
                } else {
                    let _ = writeln!(out, "      stmt.execute");
                }
                let _ = writeln!(out, "    end");
                let _ = write!(out, "  end");
                return Ok(out);
            }
            QueryCommand::Many => {
                let _ = writeln!(out, "    stmt = client.prepare(\"{}\")", sql);
                let _ = writeln!(
                    out,
                    "    results = stmt.execute({})",
                    param_array.trim_start_matches('[').trim_end_matches(']')
                );
                let _ = writeln!(out, "    results.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, "    stmt = client.prepare(\"{}\")", sql);
                let _ = writeln!(
                    out,
                    "    stmt.execute({})",
                    param_array.trim_start_matches('[').trim_end_matches(']')
                );
                let _ = writeln!(out, "    nil");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "    stmt = client.prepare(\"{}\")", sql);
                let _ = writeln!(
                    out,
                    "    stmt.execute({})",
                    param_array.trim_start_matches('[').trim_end_matches(']')
                );
                let _ = writeln!(out, "    stmt.affected_rows");
            }
            QueryCommand::Grouped => unreachable!("handled as Many in codegen"),
        }

        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);
        }
        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)
    }
}
