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::collections::HashMap;
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};

const DEFAULT_MANIFEST_PG: &str = include_str!("../../manifests/php-amphp.toml");
const DEFAULT_MANIFEST_MYSQL: &str = include_str!("../../manifests/php-amphp.mysql.toml");

pub struct PhpAmphpBackend {
    manifest: BackendManifest,
    namespace: String,
}

impl PhpAmphpBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        let default_toml = match engine {
            "postgresql" | "postgres" | "pg" => DEFAULT_MANIFEST_PG,
            "mysql" | "mariadb" => DEFAULT_MANIFEST_MYSQL,
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InternalError,
                    format!("unsupported engine '{}' for php-amphp backend", engine),
                ));
            }
        };
        let manifest =
            super::load_or_default_manifest("backends/php-amphp/manifest.toml", default_toml)?;
        Ok(Self {
            manifest,
            namespace: "App\\Generated".to_string(),
        })
    }
}

/// Map a neutral type to a PHP cast expression.
fn php_cast(neutral_type: &str) -> &'static str {
    match neutral_type {
        "int16" | "int32" | "int64" => "(int) ",
        "float32" | "float64" => "(float) ",
        "bool" => "(bool) ",
        "string" | "json" | "inet" | "interval" | "uuid" | "decimal" | "bytes" => "(string) ",
        _ => "",
    }
}

impl CodegenBackend for PhpAmphpBackend {
    fn name(&self) -> &str {
        "php-amphp"
    }

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

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

    fn apply_options(&mut self, options: &HashMap<String, String>) -> Result<(), ScytheError> {
        if let Some(ns) = options.get("namespace") {
            self.namespace = ns.clone();
        }
        Ok(())
    }

    fn file_header(&self) -> String {
        let ns = if self.namespace.is_empty() {
            String::new()
        } else {
            format!("namespace {};\n\n", self.namespace)
        };
        format!(
            "<?php\n\ndeclare(strict_types=1);\n\n{ns}// Auto-generated by scythe. Do not edit.\n"
        )
    }

    fn query_class_header(&self) -> String {
        "final class Queries {".to_string()
    }

    fn file_footer(&self) -> String {
        "}".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 mut out = String::new();

        // Readonly class with constructor
        let _ = writeln!(out, "readonly class {} {{", struct_name);
        let _ = writeln!(out, "    public function __construct(");
        for c in columns.iter() {
            let sep = ",";
            let _ = writeln!(
                out,
                "        public {} ${}{}",
                c.full_type, c.field_name, sep
            );
        }
        let _ = writeln!(out, "    ) {{}}");
        let _ = writeln!(out);

        // fromRow factory method
        let _ = writeln!(
            out,
            "    public static function fromRow(array $row): self {{"
        );
        let _ = writeln!(out, "        return new self(");
        for c in columns.iter() {
            let sep = ",";
            let is_enum = c.neutral_type.starts_with("enum::");
            let is_datetime = matches!(
                c.neutral_type.as_str(),
                "date" | "time" | "time_tz" | "datetime" | "datetime_tz"
            );
            if is_enum {
                let enum_type = &c.lang_type;
                if c.nullable {
                    let _ = writeln!(
                        out,
                        "            {}: $row['{}'] !== null ? {}::from($row['{}']) : null{}",
                        c.field_name, c.name, enum_type, c.name, sep
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "            {}: {}::from($row['{}']){}",
                        c.field_name, enum_type, c.name, sep
                    );
                }
            } else if is_datetime {
                if c.nullable {
                    let _ = writeln!(
                        out,
                        "            {}: $row['{}'] !== null ? new \\DateTimeImmutable($row['{}']) : null{}",
                        c.field_name, c.name, c.name, sep
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "            {}: new \\DateTimeImmutable($row['{}']){}",
                        c.field_name, c.name, sep
                    );
                }
            } else {
                let cast = php_cast(&c.neutral_type);
                if c.nullable {
                    let _ = writeln!(
                        out,
                        "            {}: $row['{}'] !== null ? {}{} : null{}",
                        c.field_name,
                        c.name,
                        cast,
                        format_args!("$row['{}']", c.name),
                        sep
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "            {}: {}$row['{}']{}",
                        c.field_name, cast, c.name, sep
                    );
                }
            }
        }
        let _ = writeln!(out, "        );");
        let _ = writeln!(out, "    }}");
        let _ = write!(out, "}}");
        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_oneline_with_optional(
                &analyzed.sql,
                &analyzed.optional_params,
                &analyzed.params,
            ),
            |_| "?".to_string(),
        );
        let mut out = String::new();

        // Build PHP parameter list
        let param_list = params
            .iter()
            .map(|p| format!("{} ${}", p.full_type, p.field_name))
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        // Handle :batch separately
        if matches!(analyzed.command, QueryCommand::Batch) {
            let batch_fn_name = format!("{}Batch", func_name);
            // PHPDoc for batch function
            let _ = writeln!(out, "    /**");
            let _ = writeln!(out, "     * @param \\Amp\\Sql\\SqlConnectionPool $pool");
            let _ = writeln!(out, "     * @param array<int, array<int, mixed>> $items");
            let _ = writeln!(out, "     * @return void");
            let _ = writeln!(out, "     */");
            let _ = writeln!(
                out,
                "    public static function {}(\\Amp\\Sql\\SqlConnectionPool $pool, array $items): void {{",
                batch_fn_name
            );
            let _ = writeln!(out, "        $transaction = $pool->beginTransaction();");
            let _ = writeln!(out, "        try {{");
            let _ = writeln!(
                out,
                "            $stmt = $transaction->prepare(\"{}\");",
                sql
            );
            let _ = writeln!(out, "            foreach ($items as $item) {{");
            if params.is_empty() {
                let _ = writeln!(out, "                $stmt->execute([]);");
            } else {
                let _ = writeln!(out, "                $stmt->execute($item);");
            }
            let _ = writeln!(out, "            }}");
            let _ = writeln!(out, "            $transaction->commit();");
            let _ = writeln!(out, "        }} catch (\\Throwable $e) {{");
            let _ = writeln!(out, "            $transaction->rollback();");
            let _ = writeln!(out, "            throw $e;");
            let _ = writeln!(out, "        }}");
            let _ = write!(out, "    }}");
            return Ok(out);
        }

        // Return type depends on command
        let return_type = match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => format!("?{}", struct_name),
            QueryCommand::Many => "\\Generator".to_string(),
            QueryCommand::Exec => "void".to_string(),
            QueryCommand::ExecResult | QueryCommand::ExecRows => "int".to_string(),
            QueryCommand::Batch | QueryCommand::Grouped => unreachable!(),
        };

        // PHPDoc block
        let _ = writeln!(out, "    /**");
        let _ = writeln!(out, "     * @param \\Amp\\Sql\\SqlConnectionPool $pool");
        for p in params {
            let _ = writeln!(out, "     * @param {} ${}", p.full_type, p.field_name);
        }
        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                let _ = writeln!(out, "     * @return {}|null", struct_name);
            }
            QueryCommand::Many => {
                let _ = writeln!(
                    out,
                    "     * @return \\Generator<int, {}, mixed, void>",
                    struct_name
                );
            }
            QueryCommand::Exec => {
                let _ = writeln!(out, "     * @return void");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "     * @return int");
            }
            QueryCommand::Batch | QueryCommand::Grouped => unreachable!(),
        }
        let _ = writeln!(out, "     */");

        let _ = writeln!(
            out,
            "    public static function {}(\\Amp\\Sql\\SqlConnectionPool $pool{}{}): {} {{",
            func_name, sep, param_list, return_type
        );

        // Build execute params
        // NOTE: This prepares the statement on every call for simplicity.
        // For hot paths, consider caching the prepared statement outside this method.
        if params.is_empty() {
            let _ = writeln!(
                out,
                "        $result = $pool->prepare(\"{}\")->execute([]);",
                sql
            );
        } else {
            let bindings = params
                .iter()
                .map(|p| {
                    if p.neutral_type.starts_with("enum::") {
                        format!("${}->value", p.field_name)
                    } else {
                        format!("${}", p.field_name)
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(
                out,
                "        $result = $pool->prepare(\"{}\")->execute([{}]);",
                sql, bindings
            );
        }

        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                let _ = writeln!(out, "        foreach ($result as $row) {{");
                let _ = writeln!(out, "            return {}::fromRow($row);", struct_name);
                let _ = writeln!(out, "        }}");
                let _ = writeln!(out, "        return null;");
            }
            QueryCommand::Many => {
                let _ = writeln!(out, "        foreach ($result as $row) {{");
                let _ = writeln!(out, "            yield {}::fromRow($row);", struct_name);
                let _ = writeln!(out, "        }}");
            }
            QueryCommand::Exec => {
                // nothing else needed
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "        return $result->getRowCount();");
            }
            QueryCommand::Batch | QueryCommand::Grouped => unreachable!(),
        }

        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);
        let mut out = String::new();
        let _ = writeln!(out, "enum {}: string {{", type_name);
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "    case {} = \"{}\";", variant, value);
        }
        let _ = write!(out, "}}");
        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, "readonly class {} {{", name);
        let _ = writeln!(out, "    public function __construct(");
        if composite.fields.is_empty() {
            // empty constructor
        } else {
            for field in &composite.fields {
                let _ = writeln!(out, "        public mixed ${},", field.name);
            }
        }
        let _ = writeln!(out, "    ) {{}}");
        let _ = write!(out, "}}");
        Ok(out)
    }
}
