import os

from export_recipe.export_recipe_runner import (
    export_selected_tables,
    load_output_names,
    load_recipe_inputs,
    print_export_plan,
    validate_recipe_selection,
)


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_recipe_selection(project_key, webapp_id, selected_tables)

    dip_home = os.environ.get("DIP_HOME")
    if not dip_home:
        raise ValueError("DIP_HOME environment variable not found")

    workload_folder = os.path.join(dip_home, "workload-folders", "webapps", project_key, webapp_id)

    if not os.path.exists(workload_folder):
        raise ValueError(f"Webapp workload folder not found: {workload_folder}")

    db_path = os.path.join(workload_folder, "data_store.db")
    if not os.path.exists(db_path):
        raise ValueError(f"Database file not found: {db_path}")

    output_names = load_output_names(selected_tables)
    print_export_plan(project_key, webapp_id, selected_tables, output_names)
    db_url = f"sqlite:///{db_path}"
    export_selected_tables(selected_tables, output_names, db_url, workload_folder, decompress_blobs)


if __name__ == "__main__":
    main()
