{{!
  Copyright (c) Meta Platforms, Inc. and affiliates.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

}}{{!

    NOTE:
    Unfortunately map literals cannot be used to store metadata, due to a bug
    in the Go compiler: https://github.com/golang/go/issues/33437
    The bug results in a "NewBulk too big" compilation error for some very large schemas.
    The workaround is to create slice literals (one with keys, one with values),
    create an empty map during runtime and populate that map from the two slices.

}}
{{> common/header}}

import (
    "maps"
    "sync"

    {{#program:thrift_imports}}
    {{program:go_package_alias}} "{{program:go_import_path}}"
    {{/program:thrift_imports}}
    thrift "{{program:thrift_lib_import}}"
    {{#program:import_metadata_package?}}
    metadata "{{program:thrift_metadata_import}}"
    {{/program:import_metadata_package?}}
)

{{> common/unused_imports_protection}}
// (needed to ensure safety because of naive import list construction)
var _ = thrift.ZERO
var _ = maps.Copy[map[int]int, map[int]int]
{{#program:import_metadata_package?}}
var _ = metadata.GoUnusedProtection__
{{/program:import_metadata_package?}}

// Premade Thrift types
var (
    {{#program:thrift_metadata_types}}
    {{type:metadata_name}} *{{program:metadata_qualifier}}ThriftType = nil
    {{/program:thrift_metadata_types}}
)

// Premade Thrift type initializer
var premadeThriftTypesInitOnce = sync.OnceFunc(func() {
    {{#program:thrift_metadata_types}}
    {{type:metadata_name}} = {{program:metadata_qualifier}}NewThriftType().{{> metadata/thrift_type_setter}}(
        {{> metadata/thrift_type_instance}}
    )
    {{/program:thrift_metadata_types}}
})

// Helper type to allow us to store Thrift types in a slice at compile time,
// and put them in a map at runtime. See comment at the top of template
// about a compilation limitation that affects map literals.
type thriftTypeWithFullName struct {
    fullName   string
    thriftType *{{program:metadata_qualifier}}ThriftType
}

var premadeThriftTypesMapOnce = sync.OnceValue(
    func() map[string]*{{program:metadata_qualifier}}ThriftType {
        // Relies on premade Thrift types initialization
        premadeThriftTypesInitOnce()

        thriftTypesWithFullName := make([]thriftTypeWithFullName, 0)
        {{#program:thrift_metadata_types}}
        {{#type:named?}}
        thriftTypesWithFullName = append(thriftTypesWithFullName, thriftTypeWithFullName{ "{{type:full_name}}", {{type:metadata_name}} })
        {{/type:named?}}
        {{/program:thrift_metadata_types}}

        fbthriftThriftTypesMap := make(map[string]*{{program:metadata_qualifier}}ThriftType, len(thriftTypesWithFullName))
        for _, value := range thriftTypesWithFullName {
            fbthriftThriftTypesMap[value.fullName] = value.thriftType
        }
        return fbthriftThriftTypesMap
    },
)

var structMetadatasOnce = sync.OnceValue(
    func() []*{{program:metadata_qualifier}}ThriftStruct {
        // Relies on premade Thrift types initialization
        premadeThriftTypesInitOnce()
        fbthriftThriftStructs := make([]*{{program:metadata_qualifier}}ThriftStruct, 0)
        {{#program:structs}}
        {{^struct:exception?}}
        fbthriftThriftStructs = append(fbthriftThriftStructs, {{> metadata/thrift_metadata_struct}})
        {{/struct:exception?}}
        {{/program:structs}}
        return fbthriftThriftStructs
    },
)

var exceptionMetadatasOnce = sync.OnceValue(
    func() []*{{program:metadata_qualifier}}ThriftException {
        // Relies on premade Thrift types initialization
        premadeThriftTypesInitOnce()
        return []*{{program:metadata_qualifier}}ThriftException{
            {{#program:structs}}
            {{#struct:exception?}}
            {{> metadata/thrift_metadata_exception}},
            {{/struct:exception?}}
            {{/program:structs}}
        }
    },
)

var enumMetadatasOnce = sync.OnceValue(
    func() []*{{program:metadata_qualifier}}ThriftEnum {
        // Relies on premade Thrift types initialization
        premadeThriftTypesInitOnce()
        return []*{{program:metadata_qualifier}}ThriftEnum{
            {{#program:enums}}
            {{> metadata/thrift_metadata_enum}},
            {{/program:enums}}
        }
    },
)

var serviceMetadatasOnce = sync.OnceValue(
    func() []*{{program:metadata_qualifier}}ThriftService {
        // Relies on premade Thrift types initialization
        premadeThriftTypesInitOnce()
        return []*{{program:metadata_qualifier}}ThriftService{
            {{#program:services}}
            {{> metadata/thrift_metadata_service}},
            {{/program:services}}
        }
    },
)

// GetMetadataThriftType (INTERNAL USE ONLY).
// Returns metadata ThriftType for a given full type name.
func GetMetadataThriftType(fullName string) *{{program:metadata_qualifier}}ThriftType {
    return premadeThriftTypesMapOnce()[fullName]
}

// GetThriftMetadata returns complete Thrift metadata for current and imported packages.
func GetThriftMetadata() *{{program:metadata_qualifier}}ThriftMetadata {
    allEnumsMap := make(map[string]*{{program:metadata_qualifier}}ThriftEnum)
    allStructsMap := make(map[string]*{{program:metadata_qualifier}}ThriftStruct)
    allExceptionsMap := make(map[string]*{{program:metadata_qualifier}}ThriftException)
    allServicesMap := make(map[string]*{{program:metadata_qualifier}}ThriftService)

    // Add enum metadatas from the current program...
    for _, enumMetadata := range enumMetadatasOnce() {
        allEnumsMap[enumMetadata.GetName()] = enumMetadata
    }
    // Add struct metadatas from the current program...
    for _, structMetadata := range structMetadatasOnce() {
        allStructsMap[structMetadata.GetName()] = structMetadata
    }
    // Add exception metadatas from the current program...
    for _, exceptionMetadata := range exceptionMetadatasOnce() {
        allExceptionsMap[exceptionMetadata.GetName()] = exceptionMetadata
    }
    // Add service metadatas from the current program...
    for _, serviceMetadata := range serviceMetadatasOnce() {
        allServicesMap[serviceMetadata.GetName()] = serviceMetadata
    }

    // Obtain Thrift metadatas from recursively included programs...
    var recursiveThriftMetadatas []*{{program:metadata_qualifier}}ThriftMetadata
    {{#program:thrift_imports}}
    recursiveThriftMetadatas = append(recursiveThriftMetadatas, {{program:go_package_alias}}.GetThriftMetadata())
    {{/program:thrift_imports}}

    // ...now merge metadatas from recursively included programs.
    for _, thriftMetadata := range recursiveThriftMetadatas {
        maps.Copy(allEnumsMap, thriftMetadata.GetEnums())
        maps.Copy(allStructsMap, thriftMetadata.GetStructs())
        maps.Copy(allExceptionsMap, thriftMetadata.GetExceptions())
        maps.Copy(allServicesMap, thriftMetadata.GetServices())
    }

    return {{program:metadata_qualifier}}NewThriftMetadata().
        SetEnums(allEnumsMap).
        SetStructs(allStructsMap).
        SetExceptions(allExceptionsMap).
        SetServices(allServicesMap)
}

// GetThriftMetadataForService returns Thrift metadata for the given service.
func GetThriftMetadataForService(scopedServiceName string) *{{program:metadata_qualifier}}ThriftMetadata {
    thriftMetadata := GetThriftMetadata()

    allServicesMap := thriftMetadata.GetServices()
    relevantServicesMap := make(map[string]*{{program:metadata_qualifier}}ThriftService)

    serviceMetadata := allServicesMap[scopedServiceName]
    // Visit and record all recursive parents of the target service.
    for serviceMetadata != nil {
        relevantServicesMap[serviceMetadata.GetName()] = serviceMetadata
        if serviceMetadata.IsSetParent() {
            serviceMetadata = allServicesMap[serviceMetadata.GetParent()]
        } else {
            serviceMetadata = nil
        }
    }

    thriftMetadata.SetServices(relevantServicesMap)

    return thriftMetadata
}
