package reflect

import (
  "fmt"

  shimast "github.com/microsoft/typescript-go/shim/ast"
  shimchecker "github.com/microsoft/typescript-go/shim/checker"
  nativecontext "github.com/samchon/typia/packages/typia/native/core/context"
  nativefactories "github.com/samchon/typia/packages/typia/native/core/factories"
  nativemetadata "github.com/samchon/typia/packages/typia/native/core/schemas/metadata"
)

type reflectLiteralsProgrammerNamespace struct{}

var ReflectLiteralsProgrammer = reflectLiteralsProgrammerNamespace{}

// ReflectLiteralsProgrammer_IProps is the transform context and the type argument
// of the `typia.reflect.literals` call.
//
// @evidence contracts/common.md#principled-implementation The programmer needs the transform context and the type argument of the call.
// @evidence contracts/common.md#clear-and-simple-design A two-field argument record for Write.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A data record.
// @evidence contracts/common.md#meaningful-documentation The doc states both fields.
type ReflectLiteralsProgrammer_IProps struct {
  Context nativecontext.ITypiaContext
  Type    *shimchecker.Type
}

func (reflectLiteralsProgrammerNamespace) Write(props ReflectLiteralsProgrammer_IProps) *shimast.Node {
  f := nativecontext.NodeFactoryOf(props.Context.Emit)
  result := nativefactories.MetadataFactory.Analyze(nativefactories.MetadataFactory_IProps{
    Checker: props.Context.Checker,
    Options: nativefactories.MetadataFactory_IOptions{
      Escape:   true,
      Constant: true,
      Absorb:   true,
      // Only a constant literal, the `boolean` atomic (which stands for the
      // `true | false` constants), and `null` beside them are members this
      // operation can hand back. Anything else -- an unconstrained atomic, a
      // template, a bucket of any other kind -- is rejected, and so is an
      // argument carrying no member at all: `never` has no literal to list, so
      // it is a compile error rather than an empty array (issue #2377).
      Validate: func(next struct {
        Metadata *nativemetadata.MetadataSchema
        Explore  nativefactories.MetadataFactory_IExplore
        Top      *nativemetadata.MetadataSchema
      }) []string {
        length := 0
        for _, constant := range next.Metadata.Constants {
          length += len(constant.Values)
        }
        for _, atomic := range next.Metadata.Atomics {
          if atomic.Type == "boolean" {
            length++
          }
        }
        if length == 0 {
          return []string{string(ReflectLiteralsProgrammer_ErrorMessages_NO)}
        }
        if next.Metadata.Size() != length {
          return []string{string(ReflectLiteralsProgrammer_ErrorMessages_ONLY)}
        }
        return []string{}
      },
    },
    Components: nativemetadata.NewMetadataCollection(),
    Type:       props.Type,
  })
  if result.Success == false {
    panic(nativecontext.TransformerError_from(struct {
      Code   string
      Errors []nativecontext.TransformerError_MetadataFactory_IError
    }{
      Code:   "typia.reflect.literals",
      Errors: reflectLiteralsProgrammer_errors(result.Errors),
    }))
  }

  metadata := result.Data
  values := []any{}
  visited := map[string]bool{}
  add := func(value any) {
    key := fmt.Sprintf("%T:%v", value, value)
    if visited[key] {
      return
    }
    visited[key] = true
    values = append(values, value)
  }
  for _, constant := range metadata.Constants {
    for _, value := range constant.Values {
      add(value.Value)
    }
  }
  for _, atomic := range metadata.Atomics {
    if atomic.Type == "boolean" {
      add(true)
      add(false)
      break
    }
  }
  if metadata.Nullable {
    add(nil)
  }
  return f.NewAsExpression(
    nativefactories.LiteralFactory.Write(values, props.Context.Emit),
    f.NewTypeReferenceNode(
      f.NewIdentifier("const"),
      nil,
    ),
  )
}

// ReflectLiteralsProgrammer_ErrorMessages are the two reasons the literal list
// is refused: no constant literal was found, or a member other than a constant
// literal exists.
//
// @evidence contracts/common.md#principled-implementation The two rejection reasons are named constants of a string type, so the validator and the diagnostics share one spelling and no free text is repeated.
// @evidence contracts/common.md#clear-and-simple-design A string type with two constants.
// @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
// @evidence contracts/common.md#meaningful-documentation The doc states the two reasons.
type ReflectLiteralsProgrammer_ErrorMessages string

const (
  ReflectLiteralsProgrammer_ErrorMessages_NO   ReflectLiteralsProgrammer_ErrorMessages = "no constant literal type found."
  ReflectLiteralsProgrammer_ErrorMessages_ONLY ReflectLiteralsProgrammer_ErrorMessages = "only constant literal types are allowed."
)

func reflectLiteralsProgrammer_errors(errors []nativefactories.MetadataFactory_IError) []nativecontext.TransformerError_MetadataFactory_IError {
  output := make([]nativecontext.TransformerError_MetadataFactory_IError, 0, len(errors))
  for _, err := range errors {
    output = append(output, nativecontext.TransformerError_MetadataFactory_IError{
      Name: err.Name,
      Explore: nativecontext.TransformerError_MetadataFactory_IExplore{
        Object:    err.Explore.Object,
        Property:  err.Explore.Property,
        Parameter: err.Explore.Parameter,
        Output:    err.Explore.Output,
      },
      Messages: err.Messages,
    })
  }
  return output
}
