package functional

import (
  shimast "github.com/microsoft/typescript-go/shim/ast"
  nativecontext "github.com/samchon/typia/packages/typia/native/core/context"
  nativefactories "github.com/samchon/typia/packages/typia/native/core/factories"
  nativeprogrammers "github.com/samchon/typia/packages/typia/native/core/programmers"
)

type functionalAssertFunctionProgrammerNamespace struct{}

var FunctionalAssertFunctionProgrammer = functionalAssertFunctionProgrammerNamespace{}

// FunctionalAssertFunctionProgrammer_IConfig selects the generator's variants:
// Equals is the strict form that also rejects properties the type does not
// declare.
//
// @evidence contracts/common.md#principled-implementation Each variant of the generator is one boolean or option on a record, so the transformers pick a form by naming the field and no second code path is copied.
// @evidence contracts/common.md#clear-and-simple-design A record of 1 field.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states what each field selects.
type FunctionalAssertFunctionProgrammer_IConfig struct {
  // Equals rejects surplus properties in addition to checking declared values.
  Equals bool
}

// FunctionalAssertFunctionProgrammer_IProps is the input of Write for the assert
// function generator: Context (the transform context), Modulo (the call's callee
// expression), Config (the configuration), Declaration (the function
// declaration), Expression (the function expression) and Init (the optional
// initializer of the error factory parameter).
//
// @evidence contracts/common.md#principled-implementation Write needs the transform context, the call's callee expression, the configuration, the function declaration, the function expression and the optional initializer of the error factory parameter, and the record carries them in one argument.
// @evidence contracts/common.md#clear-and-simple-design A flat argument record of 6 fields.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc names each field.
type FunctionalAssertFunctionProgrammer_IProps struct {
  // Context borrows the checker, emitter and importer for this transform.
  Context nativecontext.ITypiaContext

  // Modulo identifies the typia call for helper naming and diagnostics.
  Modulo *shimast.Node

  // Config selects ordinary validation or rejection of surplus properties.
  Config FunctionalAssertFunctionProgrammer_IConfig

  // Declaration supplies parameter bindings and the checker return signature.
  Declaration *shimast.Node

  // Expression is the original callable, invoked with the wrapper receiver.
  Expression *shimast.Node

  // Init initializes the error factory; nil selects the functional default.
  Init *shimast.Node
}

// FunctionalAssertFunctionProgrammer_ErrorFactoryWrapperOutput is what the
// generator returns: Name is the generated error-factory wrapper variable name
// and Variable is its constant declaration statement.
//
// @evidence contracts/common.md#principled-implementation The generator returns its pieces separately so the caller can place helper functions, statements and values where its own wrapper needs them.
// @evidence contracts/common.md#clear-and-simple-design A record of 2 fields.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states each returned part.
type FunctionalAssertFunctionProgrammer_ErrorFactoryWrapperOutput struct {
  // Name is the error factory binding, disambiguated against parameter names.
  Name string

  // Variable declares the shared factory once around the returned wrapper.
  Variable *shimast.Node
}

func (functionalAssertFunctionProgrammerNamespace) Write(props FunctionalAssertFunctionProgrammer_IProps) *shimast.Node {
  wrapper := FunctionalAssertFunctionProgrammer.ErrorFactoryWrapper(struct {
    Context    nativecontext.ITypiaContext
    Parameters []*shimast.Node
    Init       *shimast.Node
  }{
    Context:    props.Context,
    Parameters: functionalIsProgrammer_parameterNodes(props.Declaration),
    Init:       props.Init,
  })
  p := FunctionalAssertParametersProgrammer.Decompose(FunctionalAssertParametersProgrammer_IDecomposeProps{
    Context:    props.Context,
    Modulo:     props.Modulo,
    Config:     FunctionalAssertParametersProgrammer_IConfig{Equals: props.Config.Equals},
    Parameters: functionalIsProgrammer_parameterNodes(props.Declaration),
    Wrapper:    wrapper.Name,
  })
  r := FunctionAssertReturnProgrammer.Decompose(FunctionAssertReturnProgrammer_IDecomposeProps{
    Context:     props.Context,
    Modulo:      props.Modulo,
    Config:      FunctionAssertReturnProgrammer_IConfig{Equals: props.Config.Equals},
    Expression:  props.Expression,
    Declaration: props.Declaration,
    Wrapper:     wrapper.Name,
  })
  f := nativecontext.NodeFactoryOf(props.Context.Emit)
  statements := []*shimast.Node{wrapper.Variable}
  statements = append(statements, p.Functions...)
  statements = append(statements, r.Functions...)
  body := []*shimast.Node{}
  for _, exp := range p.Expressions {
    body = append(body, f.NewExpressionStatement(exp))
  }
  body = append(body, f.NewReturnStatement(r.Value))
  statements = append(statements, f.NewReturnStatement(
    functionalIsProgrammer_function(
      props.Context,
      props.Declaration,
      r.Async,
      functionalAssertProgrammer_returnType(props.Declaration),
      f.NewBlock(f.NewNodeList(body), true),
    ),
  ))
  return nativefactories.ExpressionFactory.SelfCall(
    props.Context.Emit,
    f.NewBlock(f.NewNodeList(statements), true),
  )
}

func (functionalAssertFunctionProgrammerNamespace) ErrorFactoryWrapper(props struct {
  Context    nativecontext.ITypiaContext
  Parameters []*shimast.Node
  Init       *shimast.Node
}) FunctionalAssertFunctionProgrammer_ErrorFactoryWrapperOutput {
  names := make([]string, 0, len(props.Parameters))
  for _, p := range props.Parameters {
    names = append(names, functionalIsProgrammer_parameterName(p))
  }
  name := functionalIsProgrammer_escapeDuplicate(names, "errorFactoryWrapper")
  init := props.Init
  if init == nil {
    init = functionalAssertProgrammer_internal(props.Context, "functionalTypeGuardErrorFactory")
  }
  return FunctionalAssertFunctionProgrammer_ErrorFactoryWrapperOutput{
    Name: name,
    Variable: nativefactories.StatementFactory.Constant(nativefactories.StatementFactory_ConstantProps{
      Name:  name,
      Type:  nativeprogrammers.Guardian.Type(props.Context),
      Value: init,
    }, props.Context.Emit),
  }
}

func (functionalAssertFunctionProgrammerNamespace) HookPath(props struct {
  Context  nativecontext.ITypiaContext
  Wrapper  string
  Replacer string
}) *shimast.Node {
  f := nativecontext.NodeFactoryOf(props.Context.Emit)
  path := nativefactories.IdentifierFactory.Access(props.Context.Emit, f.NewIdentifier("p"), "path")
  return f.NewArrowFunction(
    nil,
    nil,
    f.NewNodeList([]*shimast.Node{
      nativefactories.IdentifierFactory.Parameter("p", nil, nil, props.Context.Emit),
    }),
    nil,
    nil,
    f.NewToken(shimast.KindEqualsGreaterThanToken),
    f.NewCallExpression(
      f.NewIdentifier(props.Wrapper),
      nil,
      nil,
      f.NewNodeList([]*shimast.Node{
        f.NewObjectLiteralExpression(f.NewNodeList([]*shimast.Node{
          f.NewSpreadAssignment(f.NewIdentifier("p")),
          f.NewPropertyAssignment(
            nil,
            nativefactories.IdentifierFactory.Identifier("path", props.Context.Emit),
            nil,
            nil,
            nativefactories.ExpressionFactory.Conditional(
              path,
              f.NewCallExpression(
                nativefactories.IdentifierFactory.Access(props.Context.Emit, path, "replace"),
                nil,
                nil,
                f.NewNodeList([]*shimast.Node{
                  f.NewStringLiteral("$input", shimast.TokenFlagsNone),
                  f.NewStringLiteral(props.Replacer, shimast.TokenFlagsNone),
                }),
                shimast.NodeFlagsNone,
              ),
              f.NewIdentifier("undefined"),
              props.Context.Emit,
            ),
          ),
        }), false),
      }),
      shimast.NodeFlagsNone,
    ),
  )
}

func functionalAssertProgrammer_returnType(declaration *shimast.Node) *shimast.Node {
  if declaration == nil || declaration.FunctionLikeData() == nil {
    return nil
  }
  return declaration.FunctionLikeData().Type
}

func functionalAssertProgrammer_internal(context nativecontext.ITypiaContext, name string) *shimast.Node {
  if importer := context.Importer; importer != nil {
    return importer.Internal(name)
  }
  return nativecontext.NodeFactoryOf(context.Emit).NewIdentifier(name)
}
