from export_recipe.export_recipe_runner import (
    export_selected_tables,
    load_output_names,
    load_recipe_inputs,
    print_export_plan,
    temporary_env,
    validate_recipe_selection,
)
from export_recipe.agent_chat_utils import (
    get_physical_table_name,
    resolve_agent_chat_context,
    validate_physical_tables_exist,
)


def main():
    recipe_inputs = load_recipe_inputs()
    project_key = recipe_inputs["project_key"]
    webapp_id = recipe_inputs["webapp_id"]
    selected_tables = recipe_inputs["selected_tables"]
    decompress_blobs = recipe_inputs["decompress_blobs"]

    # Validate base recipe inputs before resolving Agent Chat specifics.
    validate_recipe_selection(project_key, webapp_id, selected_tables)

    # Load Agent Chat context (webapp metadata, db path, effective prefix).
    context = resolve_agent_chat_context(project_key, webapp_id)
    output_names = load_output_names(selected_tables)

    # Ensure all prefixed physical tables are present in SQLite.
    validate_physical_tables_exist(context["db_path"], selected_tables, context["effective_tables_prefix"])
    print_export_plan(
        project_key,
        webapp_id,
        selected_tables,
        output_names,
        webapp_name=context["webapp_name"],
        webapp_label="Agent Chat",
    )

    # Setup the answers environment flags used by the export service.
    with temporary_env(TABLES_PREFIX=context["effective_tables_prefix"], APP_MODE="answers"):
        db_url = f"sqlite:///{context['db_path']}"
        # Convert logical table names to runtime physical names.
        runtime_selected_tables = [
            get_physical_table_name(table_name, context["effective_tables_prefix"]) for table_name in selected_tables
        ]
        # Keep readable logs with both logical and physical names.
        selected_table_display_names = [
            f"{table_name} ({runtime_table_name})"
            for table_name, runtime_table_name in zip(selected_tables, runtime_selected_tables)
        ]
        export_selected_tables(
            runtime_selected_tables,
            output_names,
            db_url,
            context["workload_folder"],
            decompress_blobs,
            selected_table_display_names=selected_table_display_names,
        )


if __name__ == "__main__":
    main()
