{% materialization table, adapter='fal', supported_languages=['python', 'sql'] -%}

{%- set language = model['language'] -%}

{%- if language == 'python' -%}

  {%- if adapter.is_teleport() -%}
    {%- for _ref in model.refs -%}
      {% set _ref_args = [_ref.get('package'), _ref['name']] if _ref.get('package') else [_ref['name'],] %}
      {%- set resolved = ref(*_ref_args, v=_ref.get('version')) -%}
      {%- do adapter.sync_teleport_relation(resolved) -%}
    {%- endfor -%}
  {%- endif -%}

  {%- set relation = this.incorporate(type='table') -%}

  {%- call statement('main', language=language) -%}

    {{- py_write(compiled_code, relation) }}

  {%- endcall %}

{{- return({'relations': [relation]}) }}

{%- elif language == 'sql' -%}

  {# HACK: proxy to the db adapter table materialization #}
  {{- return(adapter.db_materialization(context, "table")) }}

{%- endif -%}

{% endmaterialization %}

{% macro py_write(code, relation) -%}
{{- compiled_code -}}

# Generated by dbt-fal

def main(read_df, write_df, fal_context=None):
  dbt_context = dbtObj(read_df)
  df = model(dbt_context, fal_context)
  return write_df(
      '{{ relation.quote(False, False, False) }}',
      df
  )
{%- endmacro %}
