from __future__ import annotations

import pathlib
import uuid
from datetime import datetime, timezone

import aiosqlite

from server.settings import settings

SCHEMA_PATH = str(pathlib.Path(__file__).resolve().parents[1] / "tools" / "schema.sql")


def new_id() -> str:
    return str(uuid.uuid4())


def utc_now_iso() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat()


async def get_db() -> aiosqlite.Connection:
    pathlib.Path(settings.db_path).parent.mkdir(parents=True, exist_ok=True)
    db = await aiosqlite.connect(settings.db_path)
    await db.execute("PRAGMA foreign_keys = ON;")
    return db


async def ensure_schema(db: aiosqlite.Connection) -> None:
    schema = pathlib.Path(SCHEMA_PATH).read_text(encoding="utf-8")
    await db.executescript(schema)
    await db.commit()
