// Copyright (c) 2023-2026 ParadeDB, Inc.
//
// This file is part of ParadeDB - Postgres for Search and Analytics
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use crate::api::operator::f16_typmod::deserialize_i32_to_f32;
use crate::query::pdb_query::pdb;
use crate::query::pdb_query::pdb::ScoreAdjustStyle;
use crate::query::proximity::ProximityClause;
use pgrx::{extension_sql, pg_cast, pg_extern};

/// [`ConstType`] is a user-facing type used in SQL queries to indicate that should const a query
/// predicate's score.  The "const" value is a multiplier so users should watch out for zero (`0`).
///
/// While there's no indication on the Rust type, [`ConstType`] wants a Postgres type modifier (typmod)
/// when constructed so that a [`pdb::Query::Const { const: $typemod, query }`] can be constructed.
///
/// Users would use this type like so:
///
/// ```sql
/// SELECT * FROM t WHERE body @@@ 'beer'::const(3);
/// ```
///
/// It's up to individual operators to decide if/how they support [`ConstType`]
///
/// Invariant: `pdb.fuzzy` and `pdb.slop` are both IMPLICITLY castable to *both*
/// `pdb.boost` and `pdb.const`. That is only unambiguous because no operator or
/// function accepts both a [`BoostType`](crate::api::operator::boost::BoostType)
/// and a `ConstType` overload at the same call site. If one ever does, those
/// fuzzy/slop -> {boost, const} casts would resolve ambiguously and one of each
/// pair must drop to `AS ASSIGNMENT` (see the boost/fuzzy cast in `fuzzy.rs`).
#[derive(Debug)]
#[repr(transparent)]
pub struct ConstType(pdb::Query);

// Contains all the boilerplate required by pgrx to make a custom type from scratch
mod sql_datum_support {
    use crate::api::operator::const_score::ConstType;
    use crate::api::operator::const_typoid;
    use crate::query::pdb_query::pdb;
    use pgrx::callconv::{Arg, ArgAbi, BoxRet, FcInfo};
    use pgrx::nullable::Nullable;
    use pgrx::pgrx_sql_entity_graph::metadata::{
        ArgumentError, ReturnsError, ReturnsRef, SqlMappingRef, SqlTranslatable, TypeOrigin,
    };
    use pgrx::{pg_sys, FromDatum, IntoDatum};

    impl From<ConstType> for pdb::Query {
        fn from(value: ConstType) -> Self {
            match value.0 {
                const_ @ pdb::Query::ScoreAdjusted { .. } => const_,
                other => pdb::Query::ScoreAdjusted {
                    query: Box::new(other),
                    score: None,
                },
            }
        }
    }

    impl IntoDatum for ConstType {
        fn into_datum(self) -> Option<pg_sys::Datum> {
            self.0.into_datum()
        }

        fn type_oid() -> pg_sys::Oid {
            const_typoid()
        }
    }

    impl FromDatum for ConstType {
        unsafe fn from_polymorphic_datum(
            datum: pg_sys::Datum,
            is_null: bool,
            typoid: pg_sys::Oid,
        ) -> Option<Self> {
            pdb::Query::from_polymorphic_datum(datum, is_null, typoid).map(ConstType)
        }
    }

    unsafe impl SqlTranslatable for ConstType {
        const TYPE_IDENT: &'static str = pgrx::pgrx_resolved_type!(ConstType);
        const TYPE_ORIGIN: TypeOrigin = TypeOrigin::External;
        const ARGUMENT_SQL: Result<SqlMappingRef, ArgumentError> =
            Ok(SqlMappingRef::literal("pdb.const"));
        const RETURN_SQL: Result<ReturnsRef, ReturnsError> =
            Ok(ReturnsRef::One(SqlMappingRef::literal("pdb.const")));
    }

    unsafe impl BoxRet for ConstType {
        unsafe fn box_into<'fcx>(self, fcinfo: &mut FcInfo<'fcx>) -> pgrx::datum::Datum<'fcx> {
            match self.into_datum() {
                Some(datum) => unsafe { fcinfo.return_raw_datum(datum) },
                None => fcinfo.return_null(),
            }
        }
    }

    unsafe impl<'fcx> ArgAbi<'fcx> for ConstType {
        unsafe fn unbox_arg_unchecked(arg: Arg<'_, 'fcx>) -> Self {
            let index = arg.index();
            unsafe {
                arg.unbox_arg_using_from_datum()
                    .unwrap_or_else(|| panic!("argument {index} must not be null"))
            }
        }

        unsafe fn unbox_nullable_arg(arg: Arg<'_, 'fcx>) -> Nullable<Self> {
            unsafe { arg.unbox_arg_using_from_datum().into() }
        }
    }
}

// [`ConstType`]'s SQL type definition and necessary functions to support creating
mod typedef {
    use crate::api::operator::const_score::ConstType;
    use crate::api::operator::f16_typmod::{
        deserialize_i32_to_f32, serialize_f32_to_i32, TYPMOD_BOUNDS,
    };
    use crate::query::pdb_query::pdb;
    use crate::query::pdb_query::pdb::{query_out, ScoreAdjustStyle};
    use pgrx::{extension_sql, pg_extern, pg_sys, Array};
    use std::ffi::{CStr, CString};
    use std::str::FromStr;

    extension_sql!(
        r#"
            CREATE SCHEMA IF NOT EXISTS pdb;
            CREATE TYPE pdb.const;
        "#,
        name = "ConstType_shell",
        creates = [Type(ConstType)]
    );

    #[pg_extern(immutable, parallel_safe)]
    fn const_in(input: &CStr, _typoid: pg_sys::Oid, typmod: i32) -> ConstType {
        let query =
            pdb::Query::unclassified_string(input.to_str().expect("input must not be NULL"));
        ConstType(pdb::Query::ScoreAdjusted {
            query: Box::new(query),
            score: (typmod != -1)
                .then(|| deserialize_i32_to_f32(typmod))
                .map(ScoreAdjustStyle::Const),
        })
    }

    #[pg_extern(immutable, parallel_safe)]
    fn const_out(input: ConstType) -> CString {
        query_out(input.0)
    }

    /// Parse the user-specified "typmod" value string and encode it into an i32 after round-tripping
    /// it through a [`half::f16`] so that the user's value will fit in the positive side of an i32,
    /// which is all Postgres lets us use.
    ///
    /// We clamp the user-provided value to `[-2048.0..2048.0]` to avoid confusion around precision
    /// loss of larger integers, due to the nature of 16 bit floats.
    #[pg_extern(immutable, parallel_safe)]
    fn const_typmod_in(typmod_parts: Array<&CStr>) -> i32 {
        assert!(typmod_parts.len() == 1);
        let const_str = typmod_parts
            .get(0)
            .unwrap()
            .expect("typmod cstring must not be NULL");
        let const_f32 = f32::from_str(const_str.to_str().unwrap())
            .unwrap_or_else(|_| panic!("invalid const value: {}", const_str.to_str().unwrap()));

        let const_ = const_f32.clamp(TYPMOD_BOUNDS.0, TYPMOD_BOUNDS.1);
        serialize_f32_to_i32(const_)
    }

    #[pg_extern(immutable, parallel_safe)]
    fn const_typmod_out(typmod: i32) -> CString {
        let const_ = deserialize_i32_to_f32(typmod);
        CString::from_str(&const_.to_string()).unwrap()
    }

    extension_sql!(
        r#"
            CREATE TYPE pdb.const (
                INPUT = const_in,
                OUTPUT = const_out,
                INTERNALLENGTH = VARIABLE,
                LIKE = text,
                TYPMOD_IN = const_typmod_in,
                TYPMOD_OUT = const_typmod_out
            );
        "#,
        name = "ConstType_final",
        requires = [
            "ConstType_shell",
            const_in,
            const_out,
            const_typmod_in,
            const_typmod_out
        ]
    );
}

#[pg_extern(immutable, parallel_safe)]
pub fn query_to_const(input: pdb::Query, typmod: i32, _is_explicit: bool) -> ConstType {
    let const_ = deserialize_i32_to_f32(typmod);
    ConstType(pdb::Query::ScoreAdjusted {
        query: Box::new(input),
        score: Some(ScoreAdjustStyle::Const(const_)),
    })
}

#[pg_extern(immutable, parallel_safe)]
pub(crate) fn text_array_to_const(
    array: Vec<String>,
    typmod: i32,
    _is_explicit: bool,
) -> ConstType {
    let const_ = deserialize_i32_to_f32(typmod);
    let query = pdb::Query::UnclassifiedArray {
        array,
        fuzzy_data: None,
        slop_data: None,
    };
    ConstType(pdb::Query::ScoreAdjusted {
        query: Box::new(query),
        score: Some(ScoreAdjustStyle::Const(const_)),
    })
}

#[pg_extern(immutable, parallel_safe)]
fn prox_to_const(input: ProximityClause, typmod: i32, _is_explicit: bool) -> ConstType {
    let const_ = deserialize_i32_to_f32(typmod);

    let prox = if let ProximityClause::Proximity {
        left,
        right,
        distance,
    } = input
    {
        pdb::Query::Proximity {
            left: *left,
            right: *right,
            distance,
        }
    } else {
        panic!("invalid ProximityClause variant: {input:?}")
    };

    ConstType(pdb::Query::ScoreAdjusted {
        query: Box::new(prox),
        score: Some(ScoreAdjustStyle::Const(const_)),
    })
}

#[pg_cast(implicit, immutable, parallel_safe)]
fn const_to_query(input: ConstType) -> pdb::Query {
    input.0
}

/// SQL `CAST` function used by Postgres to apply the `typmod` value after the type has been constructed
///
/// One would think the type's input function, which also allows for a `typmod` argument would be
/// able to do this, but alas, Postgres always sets that to `-1` for historical reasons.
///
/// In our case, a simple expression like:
///
/// ```sql
/// SELECT 'foo'::const(3);
/// ```
///
/// Will first go through the `const_in` function with a `-1` typmod, and then Postgres will call
/// the `typmod_in`/`typmod_out` functions defined for [`ConstType`], then pass that output value
/// to this function so that we can apply it.  Fun!
#[pg_extern(immutable, parallel_safe)]
pub fn const_to_const(input: ConstType, typmod: i32, _is_explicit: bool) -> ConstType {
    let new_const = deserialize_i32_to_f32(typmod);
    let mut query = input.0;
    if let pdb::Query::ScoreAdjusted { score, .. } = &mut query {
        *score = Some(ScoreAdjustStyle::Const(new_const));
        ConstType(query)
    } else {
        ConstType(pdb::Query::ScoreAdjusted {
            query: Box::new(query),
            score: Some(ScoreAdjustStyle::Const(new_const)),
        })
    }
}

extension_sql!(
    r#"
        CREATE CAST (text[] AS pdb.const) WITH FUNCTION text_array_to_const(text[], integer, boolean) AS ASSIGNMENT;
        CREATE CAST (pdb.query AS pdb.const) WITH FUNCTION query_to_const(pdb.query, integer, boolean) AS ASSIGNMENT;
        CREATE CAST (pdb.proximityclause AS pdb.const) WITH FUNCTION prox_to_const(pdb.proximityclause, integer, boolean) AS ASSIGNMENT;
        CREATE CAST (pdb.const AS pdb.const) WITH FUNCTION const_to_const(pdb.const, integer, boolean) AS IMPLICIT;
    "#,
    name = "cast_to_const",
    requires = [
        query_to_const,
        prox_to_const,
        const_to_const,
        text_array_to_const,
        "ConstType_final"
    ]
);
