from __future__ import annotations

import re
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from pathlib import Path

import aiosqlite

_CONFIG_DIR = Path.home() / ".config" / "mcp-eregistrations-smartlink"


def _slug(url: str) -> str:
    """Convert URL to filesystem-safe slug."""
    return re.sub(r"[^a-zA-Z0-9_-]", "_", url.split("//", 1)[-1])


def get_db_path(smartlink_url: str) -> Path:
    return _CONFIG_DIR / "instances" / _slug(smartlink_url) / "data.db"


@asynccontextmanager
async def get_connection(db_path: Path) -> AsyncGenerator[aiosqlite.Connection, None]:
    """Async context manager for SQLite connection."""
    db_path.parent.mkdir(parents=True, exist_ok=True)
    db = await aiosqlite.connect(str(db_path))
    await db.execute("PRAGMA journal_mode=WAL")
    await db.execute("PRAGMA foreign_keys=ON")
    db.row_factory = aiosqlite.Row
    try:
        yield db
    finally:
        await db.close()
