package sql3util

import (
	
	_ 
	

	
	

	
)

const (
	errp = 4
	sqlp = 8
)

var (
	//go:embed wasm/sql3parse_table.wasm
	binary   []byte
	once     sync.Once
	runtime  wazero.Runtime
	compiled wazero.CompiledModule
)

// ParseTable parses a [CREATE] or [ALTER TABLE] command.
//
// [CREATE]: https://sqlite.org/lang_createtable.html
// [ALTER TABLE]: https://sqlite.org/lang_altertable.html
func ( string) ( *Table,  error) {
	once.Do(func() {
		 := context.Background()
		 := wazero.NewRuntimeConfigInterpreter()
		runtime = wazero.NewRuntimeWithConfig(, )
		compiled,  = runtime.CompileModule(, binary)
	})
	if  != nil {
		return nil, 
	}

	 := context.Background()
	,  := runtime.InstantiateModule(, compiled, wazero.NewModuleConfig().WithName(""))
	if  != nil {
		return nil, 
	}
	defer .Close()

	if ,  := .Memory().Read(sqlp, uint32(len()));  {
		copy(, )
	}

	 := [...]util.Stk_t{sqlp, util.Stk_t(len()), errp}
	 = .ExportedFunction("sql3parse_table").CallWithStack(, [:])
	if  != nil {
		return nil, 
	}

	,  := .Memory().ReadUint32Le(errp)
	switch  {
	case _MEMORY:
		panic(util.OOMErr)
	case _SYNTAX:
		return nil, util.ErrorString("sql3parse: invalid syntax")
	case _UNSUPPORTEDSQL:
		return nil, util.ErrorString("sql3parse: unsupported SQL")
	}

	var  Table
	.load(, uint32([0]), )
	return &, nil
}

// Table holds metadata about a table.
type Table struct {
	Name           string
	Schema         string
	Comment        string
	IsTemporary    bool
	IsIfNotExists  bool
	IsWithoutRowID bool
	IsStrict       bool
	Columns        []Column
	Type           StatementType
	CurrentName    string
	NewName        string
}

func ( *Table) ( api.Module,  uint32,  string) {
	.Name = loadString(, +0, )
	.Schema = loadString(, +8, )
	.Comment = loadString(, +16, )

	.IsTemporary = loadBool(, +24)
	.IsIfNotExists = loadBool(, +25)
	.IsWithoutRowID = loadBool(, +26)
	.IsStrict = loadBool(, +27)

	.Columns = loadSlice(, +28, func( uint32,  *Column) {
		,  := .Memory().ReadUint32Le()
		.load(, , )
	})

	.Type = loadEnum[StatementType](, +44)
	.CurrentName = loadString(, +48, )
	.NewName = loadString(, +56, )
}

// Column holds metadata about a column.
type Column struct {
	Name                  string
	Type                  string
	Length                string
	ConstraintName        string
	Comment               string
	IsPrimaryKey          bool
	IsAutoIncrement       bool
	IsNotNull             bool
	IsUnique              bool
	PKOrder               OrderClause
	PKConflictClause      ConflictClause
	NotNullConflictClause ConflictClause
	UniqueConflictClause  ConflictClause
	CheckExpr             string
	DefaultExpr           string
	CollateName           string
	ForeignKeyClause      *ForeignKey
}

func ( *Column) ( api.Module,  uint32,  string) {
	.Name = loadString(, +0, )
	.Type = loadString(, +8, )
	.Length = loadString(, +16, )
	.ConstraintName = loadString(, +24, )
	.Comment = loadString(, +32, )

	.IsPrimaryKey = loadBool(, +40)
	.IsAutoIncrement = loadBool(, +41)
	.IsNotNull = loadBool(, +42)
	.IsUnique = loadBool(, +43)

	.PKOrder = loadEnum[OrderClause](, +44)
	.PKConflictClause = loadEnum[ConflictClause](, +48)
	.NotNullConflictClause = loadEnum[ConflictClause](, +52)
	.UniqueConflictClause = loadEnum[ConflictClause](, +56)

	.CheckExpr = loadString(, +60, )
	.DefaultExpr = loadString(, +68, )
	.CollateName = loadString(, +76, )

	if ,  := .Memory().ReadUint32Le( + 84);  != 0 {
		.ForeignKeyClause = &ForeignKey{}
		.ForeignKeyClause.load(, , )
	}
}

type ForeignKey struct {
	Table      string
	Columns    []string
	OnDelete   FKAction
	OnUpdate   FKAction
	Match      string
	Deferrable FKDefType
}

func ( *ForeignKey) ( api.Module,  uint32,  string) {
	.Table = loadString(, +0, )

	.Columns = loadSlice(, +8, func( uint32,  *string) {
		* = loadString(, , )
	})

	.OnDelete = loadEnum[FKAction](, +16)
	.OnUpdate = loadEnum[FKAction](, +20)
	.Match = loadString(, +24, )
	.Deferrable = loadEnum[FKDefType](, +32)
}

func loadString( api.Module,  uint32,  string) string {
	,  := .Memory().ReadUint32Le( + 0)
	if  == 0 {
		return ""
	}
	,  := .Memory().ReadUint32Le( + 4)
	return [-sqlp : +-sqlp]
}

func loadSlice[ any]( api.Module,  uint32,  func(uint32, *)) [] {
	,  := .Memory().ReadUint32Le( + 4)
	if  == 0 {
		return nil
	}
	,  := .Memory().ReadUint32Le( + 0)
	 := make([], )
	for  := range  {
		(, &[])
		 += 4
	}
	return 
}

func loadEnum[ ~uint32]( api.Module,  uint32)  {
	,  := .Memory().ReadUint32Le()
	return ()
}

func loadBool( api.Module,  uint32) bool {
	,  := .Memory().ReadByte()
	return  != 0
}