package factories

import (
  "crypto/rand"
  "fmt"
  shimtspath "github.com/microsoft/typescript-go/shim/tspath"
  "math"
  "os"
  "path/filepath"
  "strings"

  shimast "github.com/microsoft/typescript-go/shim/ast"
  shimcore "github.com/microsoft/typescript-go/shim/core"
  shimparser "github.com/microsoft/typescript-go/shim/parser"
  shimprinter "github.com/microsoft/typescript-go/shim/printer"
  nativecontext "github.com/samchon/typia/packages/typia/native/core/context"
)

type expressionFactoryNamespace struct{}

var ExpressionFactory = expressionFactoryNamespace{}

// ExpressionFactory_IsObjectProps selects the checks of an object test on Input:
// whether null and arrays are excluded.
//
// @evidence contracts/common.md#principled-implementation The object test is built from the input expression and two switches, so the same builder yields `typeof x === "object"` with or without the null and array exclusions that a caller's type allows.
// @evidence contracts/common.md#clear-and-simple-design A three-field argument record for IsObject.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states the two switches.
type ExpressionFactory_IsObjectProps struct {
  // CheckNull excludes null from JavaScript's object category.
  CheckNull bool

  // CheckArray excludes arrays from JavaScript's object category.
  CheckArray bool

  // Input is the expression tested; the generated checks may evaluate it more
  // than once, so callers provide a stable reference.
  Input *shimast.Expression
}

// ExpressionFactory_CurryingProps builds successive unary calls of Function.
// Empty Arguments builds a single call with no arguments.
//
// @evidence contracts/common.md#principled-implementation The first argument calls Function and each remaining argument calls the previous result, representing successive unary application; an empty list requests one zero-argument call.
// @evidence contracts/common.md#clear-and-simple-design A two-field argument record for Currying.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states both fields.
type ExpressionFactory_CurryingProps struct {
  // Function is the expression called first.
  Function *shimast.Expression

  // Arguments is applied one element per successive call, in slice order.
  Arguments []*shimast.Expression
}

// ExpressionFactory_TranspileProps configures a parsed expression template.
// The first statement must be an expression statement; later statements are
// ignored. Transpile panics if that first statement is absent or has another
// kind. The returned builder substitutes $input and recognized import calls.
//
// @evidence contracts/common.md#principled-implementation Transpile parses a script into an expression once and substitutes the caller's input, so it needs the script text and an importer for references that the script makes to internal helpers.
// @evidence contracts/common.md#clear-and-simple-design A two-field argument record for Transpile.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states both fields.
type ExpressionFactory_TranspileProps struct {
  // Importer resolves recognized $import calls; nil leaves them unchanged.
  Importer ExpressionFactory_Importer

  // Script supplies the first expression statement used as the template.
  Script string
}

// ExpressionFactory_Importer is the part of the import programmer that expression
// helpers need: references to internal helpers and to named, namespace and
// default imports.
//
// @evidence contracts/common.md#principled-implementation Expression helpers reference internal helpers and imports only through four calls, so the interface lists exactly those and any importer, including the ImportProgrammer, satisfies it without a dependency cycle.
// @evidence contracts/common.md#clear-and-simple-design A four-method interface that the importer implements; the aliases below it keep the argument types owned by the context package.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
// @evidence contracts/common.md#meaningful-documentation The doc states that it is the importer's slice that expressions use.
type ExpressionFactory_Importer interface {
  // Internal returns the reference to an internal runtime helper and registers its import.
  //
  // @evidence contracts/common.md#principled-implementation Internal helpers are the generated code's only dependency on typia's runtime, so the importer must register every one it hands out, and the method name and the doc state that.
  // @evidence contracts/common.md#clear-and-simple-design One method on a four-method interface.
  // @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
  // @evidence contracts/common.md#meaningful-documentation The comment states the reference and the registration.
  Internal(name string) *shimast.Node

  // Instance returns the reference to a named export of a file and registers the import.
  //
  // @evidence contracts/common.md#principled-implementation A named export is identified by file and name, and the importer records the request so the import statement is emitted once.
  // @evidence contracts/common.md#clear-and-simple-design One method on a four-method interface.
  // @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
  // @evidence contracts/common.md#meaningful-documentation The comment states the reference and the registration.
  Instance(props ExpressionFactory_IInstance) *shimast.Node

  // Namespace returns the reference to a file's namespace import and registers the import.
  //
  // @evidence contracts/common.md#principled-implementation A namespace import is identified by file and name, and the importer records the request so the import statement is emitted once.
  // @evidence contracts/common.md#clear-and-simple-design One method on a four-method interface.
  // @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
  // @evidence contracts/common.md#meaningful-documentation The comment states the reference and the registration.
  Namespace(props ExpressionFactory_INamespace) *shimast.Node

  // Default returns the reference to a file's default import and registers the import.
  //
  // @evidence contracts/common.md#principled-implementation A default import is identified by file and local name, and the importer records the request so the import statement is emitted once.
  // @evidence contracts/common.md#clear-and-simple-design One method on a four-method interface.
  // @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
  // @evidence contracts/common.md#meaningful-documentation The comment states the reference and the registration.
  Default(props ExpressionFactory_IDefault) *shimast.Node
}

// ImportProgrammer owns these import argument shapes in core/context. This
// package only aliases them so expression helpers do not duplicate the contract.
//
// @evidence contracts/common.md#principled-implementation The alias names the importer's default import request, so this package repeats no field list.
// @evidence contracts/common.md#clear-and-simple-design A type alias to the context package's record.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
// @evidence contracts/common.md#meaningful-documentation The comment states that the context package owns the shape.
type ExpressionFactory_IDefault = nativecontext.ImportProgrammer_IDefault

// ExpressionFactory_IInstance is the importer's named-import request, aliased so
// this package does not repeat the contract.
//
// @evidence contracts/common.md#principled-implementation The alias names the importer's named-import request.
// @evidence contracts/common.md#clear-and-simple-design A type alias to the context package's record.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
// @evidence contracts/common.md#meaningful-documentation The doc states that the context package owns the shape.
type ExpressionFactory_IInstance = nativecontext.ImportProgrammer_IInstance

// ExpressionFactory_INamespace is the importer's namespace-import request,
// aliased so this package does not repeat the contract.
//
// @evidence contracts/common.md#principled-implementation The alias names the importer's namespace-import request.
// @evidence contracts/common.md#clear-and-simple-design A type alias to the context package's record.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
// @evidence contracts/common.md#meaningful-documentation The doc states that the context package owns the shape.
type ExpressionFactory_INamespace = nativecontext.ImportProgrammer_INamespace

// ExpressionFactory_GetEscapedTextProps holds the expression whose escaped text
// is wanted.
//
// @evidence contracts/common.md#principled-implementation GetEscapedText returns the text of an identifier or string literal and otherwise the name of the expression, so a single input expression is the whole argument.
// @evidence contracts/common.md#clear-and-simple-design A one-field argument record.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states the field.
type ExpressionFactory_GetEscapedTextProps struct {
  // Input is an identifier or string literal whose text is returned directly,
  // or another expression whose name is delegated to IdentifierFactory. Nil
  // returns the empty string.
  Input *shimast.Expression
}

func (expressionFactoryNamespace) Number(value any, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  text, numeric := expressionFactory_number_text(value)
  // Go spells the non-finite floats `NaN`, `+Inf`, and `-Inf`. Only the first
  // happens to be JavaScript; `+Inf` evaluates an undeclared `Inf` and throws a
  // ReferenceError when the emitted function first runs (samchon/typia#2452).
  // Spell them as the globals, as TypeScript's own factory does.
  if math.IsNaN(numeric) {
    return f.NewIdentifier("NaN")
  }
  if math.IsInf(numeric, 0) {
    if numeric < 0 {
      return f.NewPrefixUnaryExpression(shimast.KindMinusToken, f.NewIdentifier("Infinity"))
    }
    return f.NewIdentifier("Infinity")
  }
  // Negative zero takes the same negation as every negative value; its text
  // `-0` is not a numeric literal on its own.
  if numeric < 0 || (numeric == 0 && math.Signbit(numeric)) {
    return f.NewPrefixUnaryExpression(
      shimast.KindMinusToken,
      f.NewNumericLiteral(expressionFactory_number_abs_text(numeric), shimast.TokenFlagsNone),
    )
  }
  return f.NewNumericLiteral(text, shimast.TokenFlagsNone)
}

// Bigint emits `BigInt("<value>")` for a bigint literal.
//
// The argument has to stay a string literal. This used to spell the digits as a
// bare `number` literal, so `9007199254740993n` reached the emit as
// `BigInt(9007199254740993)` and JavaScript rounded the literal to
// 9007199254740992 before `BigInt` ever parsed it -- exactly the rounding
// `numericRangeFactory_bigint_literal` and `_isTypeInt64Bigint` already spell
// out and avoid. Every bigint an argument can carry is exact in base 10, and
// `BigInt` parses the digits of a string directly, so the string form is exact
// at any magnitude.
func (expressionFactoryNamespace) Bigint(value any, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  return f.NewCallExpression(
    f.NewIdentifier("BigInt"),
    nil,
    nil,
    f.NewNodeList([]*shimast.Node{
      f.NewStringLiteral(fmt.Sprint(value), shimast.TokenFlagsNone),
    }),
    shimast.NodeFlagsNone,
  )
}

func (expressionFactoryNamespace) IsRequired(input *shimast.Expression, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  return f.NewBinaryExpression(
    nil,
    f.NewIdentifier("undefined"),
    nil,
    f.NewToken(shimast.KindExclamationEqualsEqualsToken),
    input,
  )
}

func (expressionFactoryNamespace) IsArray(input *shimast.Expression, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  return f.NewCallExpression(
    f.NewIdentifier("Array.isArray"),
    nil,
    nil,
    f.NewNodeList([]*shimast.Node{input}),
    shimast.NodeFlagsNone,
  )
}

func (expressionFactoryNamespace) IsObject(props ExpressionFactory_IsObjectProps, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  conditions := []*shimast.Node{
    f.NewBinaryExpression(
      nil,
      f.NewStringLiteral("object", shimast.TokenFlagsNone),
      nil,
      f.NewToken(shimast.KindEqualsEqualsEqualsToken),
      f.NewTypeOfExpression(props.Input),
    ),
  }
  if props.CheckNull {
    conditions = append(conditions, f.NewBinaryExpression(
      nil,
      f.NewKeywordExpression(shimast.KindNullKeyword),
      nil,
      f.NewToken(shimast.KindExclamationEqualsEqualsToken),
      props.Input,
    ))
  }
  if props.CheckArray {
    conditions = append(conditions, f.NewBinaryExpression(
      nil,
      f.NewKeywordExpression(shimast.KindFalseKeyword),
      nil,
      f.NewToken(shimast.KindEqualsEqualsEqualsToken),
      ExpressionFactory.IsArray(props.Input, emit...),
    ))
  }
  if len(conditions) == 1 {
    return conditions[0]
  }
  output := conditions[0]
  for _, condition := range conditions[1:] {
    output = f.NewBinaryExpression(
      nil,
      output,
      nil,
      f.NewToken(shimast.KindAmpersandAmpersandToken),
      condition,
    )
  }
  return output
}

func (expressionFactoryNamespace) IsInstanceOf(t string, input *shimast.Expression, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  return f.NewBinaryExpression(
    nil,
    input,
    nil,
    f.NewToken(shimast.KindInstanceOfKeyword),
    f.NewIdentifier(t),
  )
}

func (expressionFactoryNamespace) Coalesce(x *shimast.Expression, y *shimast.Expression, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  return f.NewBinaryExpression(
    nil,
    x,
    nil,
    f.NewToken(shimast.KindQuestionQuestionToken),
    y,
  )
}

// Conditional builds `condition ? whenTrue : whenFalse` with its operator tokens
// supplied at construction. typia's programmers historically built conditional
// expressions with nil `?`/`:` tokens and relied on a post-emit tree walk
// (NormalizeSyntheticTokens) to fill them in; constructing them well-formed here
// removes that workaround. The node is structurally identical to the patched-up
// form, so emitted text is unchanged.
func (expressionFactoryNamespace) Conditional(condition *shimast.Expression, whenTrue *shimast.Expression, whenFalse *shimast.Expression, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  return f.NewConditionalExpression(
    condition,
    f.NewToken(shimast.KindQuestionToken),
    whenTrue,
    f.NewToken(shimast.KindColonToken),
    whenFalse,
  )
}

func (expressionFactoryNamespace) Currying(props ExpressionFactory_CurryingProps, emit ...*shimprinter.EmitContext) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  if len(props.Arguments) == 0 {
    return f.NewCallExpression(props.Function, nil, nil, nil, shimast.NodeFlagsNone)
  }
  prev := f.NewCallExpression(
    props.Function,
    nil,
    nil,
    f.NewNodeList([]*shimast.Node{props.Arguments[0]}),
    shimast.NodeFlagsNone,
  )
  for _, param := range props.Arguments[1:] {
    prev = f.NewCallExpression(
      prev,
      nil,
      nil,
      f.NewNodeList([]*shimast.Node{param}),
      shimast.NodeFlagsNone,
    )
  }
  return prev
}

// SelfCall takes a required emit context (nil for context-free callers) for the
// same reason as IdentifierFactory.Access: its trailing typeNode variadic blocks
// the optional-emit form.
func (expressionFactoryNamespace) SelfCall(ec *shimprinter.EmitContext, body *shimast.ConciseBody, typeNode ...*shimast.TypeNode) *shimast.Node {
  if body != nil && body.Kind == shimast.KindCallExpression {
    return body
  }
  f := nativecontext.NodeFactoryOf(ec)
  var output *shimast.TypeNode
  if len(typeNode) != 0 {
    output = typeNode[0]
  }
  arrow := f.NewArrowFunction(
    nil,
    nil,
    f.NewNodeList(nil),
    output,
    nil,
    f.NewToken(shimast.KindEqualsGreaterThanToken),
    body,
  )
  return f.NewCallExpression(
    f.NewParenthesizedExpression(arrow),
    nil,
    nil,
    nil,
    shimast.NodeFlagsNone,
  )
}

func (expressionFactoryNamespace) GetEscapedText(props ExpressionFactory_GetEscapedTextProps) string {
  if props.Input == nil {
    return ""
  }
  if props.Input.Kind == shimast.KindIdentifier || shimast.IsStringLiteral(props.Input) {
    return props.Input.Text()
  }
  return IdentifierFactory.GetName(props.Input)
}

func (expressionFactoryNamespace) Transpile(props ExpressionFactory_TranspileProps, emit ...*shimprinter.EmitContext) func(input *shimast.Expression) *shimast.Node {
  f := nativecontext.NodeFactoryOf(emit...)
  fileName := filepath.Join(os.TempDir(), expressionFactory_random_format_uuid()+".ts")
  if absolute, err := filepath.Abs(fileName); err == nil {
    fileName = absolute
  }
  file := shimparser.ParseSourceFile(
    shimast.SourceFileParseOptions{FileName: shimtspath.RootedFilePath(filepath.ToSlash(fileName))},
    props.Script,
    shimcore.ScriptKindTS,
  )
  if file == nil || file.Statements == nil || len(file.Statements.Nodes) == 0 {
    panic("Error on ExpressionFactory.transpile(): no statement exists.")
  }
  statement := file.Statements.Nodes[0]
  if statement.Kind != shimast.KindExpressionStatement {
    panic("Error on ExpressionFactory.transpile(): statement is not an expression statement.")
  }
  expression := f.DeepCloneNode(statement.AsExpressionStatement().Expression)
  return func(input *shimast.Expression) *shimast.Node {
    var visitor *shimast.NodeVisitor
    visitor = shimast.NewNodeVisitor(func(node *shimast.Node) *shimast.Node {
      if node == nil {
        return nil
      }
      if node.Kind == shimast.KindIdentifier && node.Text() == "$input" {
        return input
      }
      if props.Importer != nil && node.Kind == shimast.KindCallExpression {
        if imported := expressionFactory_import(props.Importer, node); imported != nil {
          return imported
        }
      }
      return node.VisitEachChild(visitor)
    }, f, shimast.NodeVisitorHooks{})
    return visitor.VisitNode(expression)
  }
}

func expressionFactory_import(importer ExpressionFactory_Importer, node *shimast.Node) *shimast.Node {
  call := node.AsCallExpression()
  if call == nil || call.Expression == nil || call.Expression.Kind != shimast.KindIdentifier {
    return nil
  }
  name := call.Expression.Text()
  args := []*shimast.Node{}
  if call.Arguments != nil {
    args = call.Arguments.Nodes
  }
  if name == "$importInternal" && len(args) == 1 && shimast.IsStringLiteral(args[0]) {
    return importer.Internal(args[0].Text())
  }
  if name == "$importInstance" && len(args) == 2 && shimast.IsStringLiteral(args[0]) && shimast.IsStringLiteral(args[1]) {
    return importer.Instance(ExpressionFactory_IInstance{
      Name: args[0].Text(),
      File: args[1].Text(),
    })
  }
  if name == "$importNamespace" && len(args) == 2 && shimast.IsStringLiteral(args[0]) && shimast.IsStringLiteral(args[1]) {
    return importer.Namespace(ExpressionFactory_INamespace{
      Name: args[0].Text(),
      File: args[1].Text(),
    })
  }
  if name == "$importDefault" && len(args) == 3 && shimast.IsStringLiteral(args[0]) && shimast.IsStringLiteral(args[1]) {
    return importer.Default(ExpressionFactory_IDefault{
      Name: args[0].Text(),
      File: args[1].Text(),
      Type: false,
    })
  }
  return nil
}

func expressionFactory_number_text(value any) (string, float64) {
  switch v := value.(type) {
  case int:
    return fmt.Sprint(v), float64(v)
  case int64:
    return fmt.Sprint(v), float64(v)
  case float32:
    return fmt.Sprint(v), float64(v)
  case float64:
    return fmt.Sprint(v), v
  default:
    text := fmt.Sprint(value)
    var f float64
    fmt.Sscan(text, &f)
    return text, f
  }
}

func expressionFactory_number_abs_text(value float64) string {
  text := fmt.Sprint(math.Abs(value))
  return strings.TrimSuffix(text, ".0")
}

func expressionFactory_random_format_uuid() string {
  bytes := make([]byte, 16)
  if _, err := rand.Read(bytes); err != nil {
    return "00000000-0000-4000-8000-000000000000"
  }
  bytes[6] = (bytes[6] & 0x0f) | 0x40
  bytes[8] = (bytes[8] & 0x3f) | 0x80
  return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", bytes[0:4], bytes[4:6], bytes[6:8], bytes[8:10], bytes[10:16])
}
