#include "builtins/builtins.h"
#include "parse/parse.h"
#include "execute/execute.h"
#include "compiler.h"

using namespace empathy;

namespace empathy::builtins
{
    void SetupApiCompiler( Env& e )
    {
        weak_ptr< Env > pEnv = e.shared_from_this();

        RegisterBuiltinFunc< Intrinsic< void ( bool ) > >( e, "#DiagnosticsEnableTraces"_sid,
            [pEnv]( const Value& enable )
            {
                if( !enable.isConstant() )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( enable.locationId(),
                        "#DiagnosticsEnableTraces: the expression doesn't evaluate to a constant." );
                    return;
                }

                DiagnosticsManager::GetInstance().setTraceMode( *FromValue< bool >( enable ) );
            } );

        RegisterBuiltinFunc< void ( bool ) >( e, "DiagnosticsForceColors"_sid,
            [pEnv]( bool enable )
            {
                DiagnosticsManager::GetInstance().setForceColors( enable );
            } );

        RegisterBuiltinFunc< Intrinsic< void ( uint32_t ) > >( e, "#SetExecutionBudget"_sid,
            [pEnv]( const Value& budget )
            {
                static bool used = false;

                if( !budget.isConstant() )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( budget.locationId(),
                        "#SetExecutionBudget: the expression doesn't evaluate to a constant." );
                    return;
                }

                if( used )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( 0,
                        "#SetExecutionBudget can only be used once." );
                    return;
                }

                used = true;
                execute::VM::SetExecutionBudget( *FromValue< uint32_t >( budget ) );
            } );

        RegisterBuiltinFunc< Eager< Value > ( Value, string ) >( e, "ExternalFunction"_sid,
            [pEnv]( const Value& f, const string& symbol )
            {
                auto ft = FromValue< FuncType >( f );
                if( !ft )
                    return PoisonValue();

                return ToValue( BuildExternalFunc( *ft, symbol ) );
            } );

        RegisterBuiltinFunc< void ( string, Value ) >( e, "CreateConstant"_sid,
            [pEnv]( const string& name, const Value& v )
            {
                if( !v.isConstant() )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( v.locationId(),
                        "CreateConstant: the expression doesn't evaluate to a constant." );
                    return;
                }

                pEnv.lock()->storeValue(
                    AppendToVectorTerm( RootIdentity(), StringId( name.c_str() ) ),
                    ANYTERM( _ ), ValueToIRExpr( v ) );
            } );

        RegisterBuiltinFunc< Intrinsic< uint32_t ( string ) > >( e, "#Include"_sid,
            [pEnv]( const Value& fnameval ) -> Value
            {
                auto filename = *FromValue< string >( fnameval );
                auto identity = InjectDomainIntoIdentity( RootIdentity(), DomainCompileTime() );

                auto result = Compiler::LoadAndExecuteFile( pEnv.lock(), filename, identity, GetValueType< uint32_t >() );

                if( !result )
                    return ToValue< uint32_t >( 1 );

                return *result;
            } );

        RegisterBuiltinFunc< uint32_t ( string ) >( e, "ExecuteFile"_sid,
            [pEnv]( const string& filename ) -> Value
            {
                auto identity = InjectDomainIntoIdentity( RootIdentity(), DomainCompileTime() );

                auto result = Compiler::LoadAndExecuteFile( pEnv.lock(), filename, identity, GetValueType< uint32_t >() );

                if( !result )
                    return ToValue< uint32_t >( 1 );

                return *result;
            } );

        RegisterBuiltinFunc< Intrinsic< Value ( string, Value, Value ) > >( e, "#CompileFileToFunction"_sid,
            [pEnv]( const Value& filenameVal, const Value& rt, const Value& params ) -> Value
            {
                if( !filenameVal.isConstant() )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( filenameVal.locationId(),
                        "#CompileFileToFunction: the expression doesn't evaluate to a constant." );
                    return PoisonValue();
                }

                auto filename = *FromValue< string >( filenameVal );

                // Validate those generic value inputs
                if( !rt.isType() )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( rt.locationId(),
                        "#CompileFileToFunction: type expected.", 0 );
                    return PoisonValue();
                }

                if( CheckParamListKind( params ) != ParamListKind::Regular )
                {
                    DiagnosticsManager::GetInstance().emitErrorMessage( params.locationId(),
                        "#CompileFileToFunction: template parameter lists are not supported.", 0 );
                    return PoisonValue();
                }

                auto ftype = BuildFuncType( sema::DomainAny(), rt, params );

                // TODO at some point we'll want to pass the base identity to use as a param but
                // let's wait and see how the module and namespace stuff pans out first

                auto identity = sema::InjectDomainIntoIdentity( builtins::RootIdentity(), DomainRunTime() );
                sema::Context c( pEnv.lock(), identity, ftype.returnType() );

                auto funcIdentity = AppendToVectorTerm( sema::InjectDomainIntoIdentity( identity, DomainRunTime() ),
                    TERM( StringId( pEnv.lock()->NewUniqueId() ) ) );

                c.env()->addVisibilityRule(
                    InjectDomainIntoIdentity( identity, ANYTERM( _ ) ),
                    InjectDomainIntoIdentity( funcIdentity, ANYTERM( _ ) ) );

                auto func = BuildFunc( c, ftype, identity, params, nullptr, c );
                const auto& pFuncLLR = func.llr();

                auto cfg = Compiler::LoadAndParseFile( pEnv.lock(), filename,  funcIdentity, ftype.returnType() );

                if( !cfg )
                    return PoisonValue();

                if( cfg->isPoisoned() )
                    return PoisonValue();

                if( c.returnType() != GetValueType< void >()
                    && !cfg->areAllBBTerminated() )
                {
                    pFuncLLR->setInvalid();

                    // TODO the return statement should always be optional at the top level of a file,
                    // so we should be passed a default return value as parameter and insert return
                    // statements automatically wherever they may be missing in the cfg.
                    DiagnosticsManager::GetInstance().emitErrorMessage( 0,
                        format( "{}: missing return statement in a function with non-void return type.", filename ) );
                    return ToValue( func ).setPoison();
                }

                pFuncLLR->body() = cfg;
                return ToValue( func );
            } );
    }
}
