use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{
    enum_type_name, fn_name, row_struct_name, to_camel_case, to_pascal_case,
};
use scythe_backend::types::resolve_type;
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, ResolvedColumn, ResolvedParam};
use crate::backends::typescript_common::{TsRowType, generate_zod_row_struct};
use crate::singularize;

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

pub struct TypescriptSnowflakeBackend {
    manifest: BackendManifest,
    row_type: TsRowType,
}

impl TypescriptSnowflakeBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        match engine {
            "snowflake" => {}
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InternalError,
                    format!(
                        "typescript-snowflake only supports Snowflake, got engine '{}'",
                        engine
                    ),
                ));
            }
        }
        let manifest = super::load_or_default_manifest(
            "backends/typescript-snowflake/manifest.toml",
            DEFAULT_MANIFEST_TOML,
        )?;
        Ok(Self {
            manifest,
            row_type: TsRowType::default(),
        })
    }
}

/// Rewrite $1, $2, ... positional params to ? for Snowflake.
impl CodegenBackend for TypescriptSnowflakeBackend {
    fn name(&self) -> &str {
        "typescript-snowflake"
    }

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

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

    fn file_header(&self) -> String {
        let mut header =
            "/** Auto-generated by scythe. Do not edit. */\n\nimport type { Connection } from \"snowflake-sdk\";\n"
                .to_string();
        if self.row_type == TsRowType::Zod {
            header.push_str("import { z } from \"zod\";\n");
        }
        header
    }

    fn generate_row_struct(
        &self,
        query_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let struct_name = row_struct_name(query_name, &self.manifest.naming);
        if self.row_type == TsRowType::Zod {
            return Ok(generate_zod_row_struct(&struct_name, query_name, columns));
        }
        let mut out = String::new();
        let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
        let _ = writeln!(out, "export interface {} {{", struct_name);
        for col in columns {
            let _ = writeln!(out, "\t{}: {};", col.field_name, col.full_type);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_model_struct(
        &self,
        table_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let singular = singularize(table_name);
        let name = to_pascal_case(&singular);
        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 mut out = String::new();

        let param_list = params
            .iter()
            .map(|p| format!("{}: {}", p.field_name, p.full_type))
            .collect::<Vec<_>>()
            .join(", ");

        let sql = super::rewrite_pg_placeholders(
            &super::clean_sql_with_optional(
                &analyzed.sql,
                &analyzed.optional_params,
                &analyzed.params,
            ),
            |_| "?".to_string(),
        );

        let inline_params = if params.is_empty() {
            "conn: Connection".to_string()
        } else {
            format!("conn: Connection, {}", param_list)
        };

        let write_fn_sig = |out: &mut String, name: &str, params_inline: &str, ret: &str| {
            let oneliner = format!(
                "export async function {}({}): Promise<{}> {{",
                name, params_inline, ret
            );
            if oneliner.len() <= 80 {
                let _ = writeln!(out, "{}", oneliner);
            } else {
                let mut parts = vec!["\tconn: Connection".to_string()];
                for p in params {
                    parts.push(format!("\t{}: {}", p.field_name, p.full_type));
                }
                let _ = writeln!(out, "export async function {}(", name);
                for part in &parts {
                    let _ = writeln!(out, "{},", part);
                }
                let _ = writeln!(out, "): Promise<{}> {{", ret);
            }
        };

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

        // Snowflake SDK uses callback-based API; wrap in a Promise.
        let emit_execute = |out: &mut String, sql: &str, binds: &str, result_var: &str| {
            let _ = writeln!(
                out,
                "\tconst {} = await new Promise<any[]>((resolve, reject) => {{",
                result_var
            );
            let _ = writeln!(
                out,
                "\t\tconn.execute({{ sqlText: `{}`, binds: [{}], complete: (err, _stmt, rows) => {{",
                sql,
                if binds.is_empty() { "" } else { &binds[2..] } // strip ", " prefix
            );
            let _ = writeln!(out, "\t\t\tif (err) reject(err);");
            let _ = writeln!(out, "\t\t\telse resolve(rows ?? []);");
            let _ = writeln!(out, "\t\t}}}});");
            let _ = writeln!(out, "\t}});");
        };

        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                let _ = writeln!(out, "/** Fetch a single {} or null. */", struct_name);
                let ret = format!("{} | null", struct_name);
                write_fn_sig(&mut out, &func_name, &inline_params, &ret);
                emit_execute(&mut out, &sql, &binds, "rows");
                // Snowflake SDK rows are typed as any[], so a single assertion suffices.
                let _ = writeln!(
                    out,
                    "\treturn rows.length > 0 ? (rows[0] as {}) : null;",
                    struct_name
                );
                let _ = write!(out, "}}");
            }
            QueryCommand::Batch => {
                let batch_fn_name = format!("{}Batch", func_name);
                if params.len() > 1 {
                    let params_type_name = format!("{}BatchParams", struct_name);
                    let _ = writeln!(out, "/** Params for {} batch operation. */", struct_name);
                    let _ = writeln!(out, "export interface {} {{", params_type_name);
                    for p in params {
                        let _ = writeln!(out, "\t{}: {};", p.field_name, p.full_type);
                    }
                    let _ = writeln!(out, "}}");
                    let _ = writeln!(out);
                    let _ = writeln!(
                        out,
                        "/** Execute {} for each item in the batch. */",
                        analyzed.name
                    );
                    let batch_params = format!("conn: Connection, items: {}[]", params_type_name);
                    write_fn_sig(&mut out, &batch_fn_name, &batch_params, "void");
                    let _ = writeln!(out, "\tfor (const item of items) {{");
                    let _ = writeln!(out, "\t\tawait new Promise<void>((resolve, reject) => {{");
                    let args: Vec<String> = params
                        .iter()
                        .map(|p| format!("item.{}", p.field_name))
                        .collect();
                    let _ = writeln!(
                        out,
                        "\t\t\tconn.execute({{ sqlText: `{}`, binds: [{}], complete: (err) => err ? reject(err) : resolve() }});",
                        sql,
                        args.join(", ")
                    );
                    let _ = writeln!(out, "\t\t}});");
                    let _ = writeln!(out, "\t}}");
                    let _ = write!(out, "}}");
                } else if params.len() == 1 {
                    let _ = writeln!(
                        out,
                        "/** Execute {} for each item in the batch. */",
                        analyzed.name
                    );
                    let batch_params =
                        format!("conn: Connection, items: {}[]", params[0].full_type);
                    write_fn_sig(&mut out, &batch_fn_name, &batch_params, "void");
                    let _ = writeln!(out, "\tfor (const item of items) {{");
                    let _ = writeln!(out, "\t\tawait new Promise<void>((resolve, reject) => {{");
                    let _ = writeln!(
                        out,
                        "\t\t\tconn.execute({{ sqlText: `{}`, binds: [item], complete: (err) => err ? reject(err) : resolve() }});",
                        sql
                    );
                    let _ = writeln!(out, "\t\t}});");
                    let _ = writeln!(out, "\t}}");
                    let _ = write!(out, "}}");
                } else {
                    let _ = writeln!(
                        out,
                        "/** Execute {} for each item in the batch. */",
                        analyzed.name
                    );
                    write_fn_sig(
                        &mut out,
                        &batch_fn_name,
                        "conn: Connection, count: number",
                        "void",
                    );
                    let _ = writeln!(out, "\tfor (let i = 0; i < count; i++) {{");
                    let _ = writeln!(out, "\t\tawait new Promise<void>((resolve, reject) => {{");
                    let _ = writeln!(
                        out,
                        "\t\t\tconn.execute({{ sqlText: `{}`, complete: (err) => err ? reject(err) : resolve() }});",
                        sql
                    );
                    let _ = writeln!(out, "\t\t}});");
                    let _ = writeln!(out, "\t}}");
                    let _ = write!(out, "}}");
                }
            }
            QueryCommand::Many => {
                let _ = writeln!(out, "/** Fetch all {} rows. */", struct_name);
                let ret = format!("{}[]", struct_name);
                write_fn_sig(&mut out, &func_name, &inline_params, &ret);
                emit_execute(&mut out, &sql, &binds, "rows");
                // Snowflake SDK rows are typed as any[], so a single assertion suffices.
                let _ = writeln!(out, "\treturn rows as {}[];", struct_name);
                let _ = write!(out, "}}");
            }
            QueryCommand::Exec => {
                let _ = writeln!(out, "/** Execute a query returning no rows. */");
                write_fn_sig(&mut out, &func_name, &inline_params, "void");
                let _ = writeln!(out, "\tawait new Promise<void>((resolve, reject) => {{");
                let _ = writeln!(
                    out,
                    "\t\tconn.execute({{ sqlText: `{}`, binds: [{}], complete: (err) => err ? reject(err) : resolve() }});",
                    sql,
                    if binds.is_empty() { "" } else { &binds[2..] }
                );
                let _ = writeln!(out, "\t}});");
                let _ = write!(out, "}}");
            }
            QueryCommand::Grouped => unreachable!("Grouped is rewritten to Many before codegen"),
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(
                    out,
                    "/** Execute a query and return the number of affected rows. */"
                );
                write_fn_sig(&mut out, &func_name, &inline_params, "number");
                let _ = writeln!(
                    out,
                    "\tconst count = await new Promise<number>((resolve, reject) => {{"
                );
                let _ = writeln!(
                    out,
                    "\t\tconn.execute({{ sqlText: `{}`, binds: [{}], complete: (err, stmt) => {{",
                    sql,
                    if binds.is_empty() { "" } else { &binds[2..] }
                );
                let _ = writeln!(out, "\t\t\tif (err) reject(err);");
                let _ = writeln!(out, "\t\t\telse resolve(stmt?.getNumUpdatedRows() ?? 0);");
                let _ = writeln!(out, "\t\t}}}});");
                let _ = writeln!(out, "\t}});");
                let _ = writeln!(out, "\treturn count;");
                let _ = write!(out, "}}");
            }
        }

        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);
        if self.row_type == TsRowType::Zod {
            return Ok(super::typescript_common::generate_zod_enum(
                &type_name,
                &enum_info.values,
            ));
        }
        let mut out = String::new();
        let variants: Vec<String> = enum_info
            .values
            .iter()
            .map(|v| format!("\"{}\"", v))
            .collect();
        let _ = write!(out, "export type {} = {};", type_name, variants.join(" | "));
        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();
        let _ = writeln!(out, "/** Composite type {}. */", composite.sql_name);
        let _ = writeln!(out, "export interface {} {{", name);
        for field in &composite.fields {
            let ts_type = resolve_type(&field.neutral_type, &self.manifest, false)
                .map(|t| t.into_owned())
                .map_err(|e| {
                    ScytheError::new(
                        ErrorCode::InternalError,
                        format!("composite field type error: {}", e),
                    )
                })?;
            let _ = writeln!(out, "\t{}: {};", to_camel_case(&field.name), ts_type);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn apply_options(
        &mut self,
        options: &std::collections::HashMap<String, String>,
    ) -> Result<(), ScytheError> {
        if let Some(value) = options.get("row_type") {
            self.row_type = TsRowType::from_option(value)?;
        }
        Ok(())
    }
}
