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-oci8.toml");

pub struct RubyOci8Backend {
    manifest: BackendManifest,
}

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

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

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

    fn supported_engines(&self) -> &[&str] {
        &["oracle"]
    }

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

    fn file_header(&self) -> String {
        "# frozen_string_literal: true\n\n# Auto-generated by scythe. Do not edit.\n\nrequire 'oci8'\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::rewrite_pg_placeholders(
            &super::clean_sql_with_optional(
                &analyzed.sql,
                &analyzed.optional_params,
                &analyzed.params,
            ),
            |n| format!(":{n}"),
        );
        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 { ", " };

        if !matches!(analyzed.command, QueryCommand::Batch) {
            let _ = writeln!(out, "  def self.{}(conn{}{})", func_name, sep, param_list);
        }

        let bind_vars = if params.is_empty() {
            String::new()
        } else {
            format!(
                ", {}",
                params
                    .iter()
                    .map(|p| p.field_name.clone())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };

        // Check if this is a DML with RETURNING (INSERT/UPDATE/DELETE RETURNING)
        let has_returning = sql.to_uppercase().contains("RETURNING");

        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                if has_returning {
                    // Oracle RETURNING requires output bind variables via INTO clause.
                    // ruby-oci8 uses cursor.parse + cursor.bind_param(N, nil, Type) for outputs.
                    let _ = writeln!(out, "    cursor = conn.parse(\"{}\")", {
                        let into_clause = columns
                            .iter()
                            .enumerate()
                            .map(|(i, _)| format!(":{}", params.len() + i + 1))
                            .collect::<Vec<_>>()
                            .join(", ");
                        format!("{} INTO {}", sql, into_clause)
                    });
                    for (i, p) in params.iter().enumerate() {
                        let _ = writeln!(out, "    cursor.bind_param({}, {})", i + 1, p.field_name);
                    }
                    for (i, col) in columns.iter().enumerate() {
                        let ruby_type = match col.neutral_type.as_str() {
                            "int32" | "int64" => "Integer",
                            "float32" | "float64" | "decimal" => "Float",
                            "date" | "datetime" | "datetime_tz" | "time" | "time_tz" => "Time",
                            _ => "String",
                        };
                        let _ = writeln!(
                            out,
                            "    cursor.bind_param({}, nil, {})",
                            params.len() + i + 1,
                            ruby_type
                        );
                    }
                    let _ = writeln!(out, "    cursor.exec");
                    let fields = columns
                        .iter()
                        .enumerate()
                        .map(|(i, c)| format!("{}: cursor[{}]", c.field_name, params.len() + i + 1))
                        .collect::<Vec<_>>()
                        .join(", ");
                    let _ = writeln!(out, "    {}.new({})", struct_name, fields);
                } else {
                    let _ = writeln!(out, "    cursor = conn.exec(\"{}\"{})", sql, bind_vars);
                    let _ = writeln!(out, "    row = cursor.fetch");
                    let _ = writeln!(out, "    return nil if row.nil?");
                    let fields = columns
                        .iter()
                        .enumerate()
                        .map(|(i, c)| format!("{}: row[{}]", c.field_name, i))
                        .collect::<Vec<_>>()
                        .join(", ");
                    let _ = writeln!(out, "    {}.new({})", struct_name, fields);
                }
            }
            QueryCommand::Many => {
                let _ = writeln!(out, "    cursor = conn.exec(\"{}\"{})", sql, bind_vars);
                let _ = writeln!(out, "    results = []");
                let _ = writeln!(out, "    while (row = cursor.fetch)");
                let fields = columns
                    .iter()
                    .enumerate()
                    .map(|(i, c)| format!("{}: row[{}]", c.field_name, i))
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "      results << {}.new({})", struct_name, fields);
                let _ = writeln!(out, "    end");
                let _ = writeln!(out, "    results");
            }
            QueryCommand::Exec => {
                let _ = writeln!(out, "    conn.exec(\"{}\"{})", sql, bind_vars);
                let _ = writeln!(out, "    nil");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "    cursor = conn.exec(\"{}\"{})", sql, bind_vars);
                let _ = writeln!(out, "    cursor.row_count");
            }
            QueryCommand::Batch => {
                let batch_fn_name = format!("{}_batch", func_name);
                let _ = writeln!(out, "  def self.{}(conn, items)", batch_fn_name);
                let _ = writeln!(out, "    items.each do |item|");
                if params.len() > 1 {
                    let _ = writeln!(out, "      conn.exec(\"{}\", *item)", sql);
                } else if params.len() == 1 {
                    let _ = writeln!(out, "      conn.exec(\"{}\", item)", sql);
                } else {
                    let _ = writeln!(out, "      conn.exec(\"{}\")", sql);
                }
                let _ = writeln!(out, "    end");
                let _ = write!(out, "  end");
                return Ok(out);
            }
            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)
    }
}
