from pathlib import Path

from nextpy_server.app import DEFAULT_ASSET_PREFIX

from n6k_server.app import DEFAULT_DATA_PREFIX


def _config_fn(project_dir: Path, config: dict):
    db_src = project_dir / "node_modules/@n6k.io/db/src"
    asset_prefix = DEFAULT_ASSET_PREFIX
    workers = [
        {
            "name": "fetch-worker",
            "path": str((db_src / "fetch-worker.js").resolve()),
            "url": f"{asset_prefix}/workers/fetch-worker.js",
        },
        {
            "name": "n6k-duckdb-worker",
            "path": str((db_src / "n6k-duckdb-worker.js").resolve()),
            "url": f"{asset_prefix}/workers/n6k-duckdb-worker.js",
        },
    ]

    fetch_worker_url = next(w["url"] for w in workers if w["name"] == "fetch-worker")
    duckdb_worker_url = next(w["url"] for w in workers if w["name"] == "n6k-duckdb-worker")

    config["wrappers"] = [
        {
            "component": "DuckDBProvider",
            "import": "import { DuckDBProvider } from '@n6k.io/db/react';",
            "props": {
                "databases": {"db": DEFAULT_DATA_PREFIX},
                "duckdbOptions": {
                    "fetchWorkerUrl": fetch_worker_url,
                    "duckdbWorkerUrl": duckdb_worker_url,
                },
            },
        },
        {
            "component": "DuckDBConnectionGuard",
            "import": "import { DuckDBConnectionGuard } from '@n6k.io/ui/lib/duckdb-connection-guard';",
        },
        *config.get("wrappers", []),
    ]
    config["workers"] = workers
