"""
clawID storage backends.

Quick-start:
    from clawid.storage import SQLiteStore, from_uri

    store = SQLiteStore("clawid.db")            # local dev
    store = from_uri("postgresql://user:pass@host/db")  # production
"""

from .base import ClawIDStore
from .sqlite import SQLiteStore
from .postgres import PostgreSQLStore
from .mongo import MongoDBStore
from .redis_store import RedisStore


def from_uri(uri: str) -> ClawIDStore:
    """
    Create a store from a connection URI.

    Supported schemes:
        sqlite:///path/to/file.db   or   sqlite:///:memory:
        postgresql://user:pass@host:5432/db
        mongodb://user:pass@host:27017/db
        redis://host:6379           (optional ?ttl=3600)

    Example:
        store = from_uri("sqlite:///clawid.db")
        store = from_uri("postgresql://postgres:secret@localhost/myapp")
        store = from_uri("mongodb://localhost/myapp")
        store = from_uri("redis://localhost:6379?ttl=86400")
    """
    from urllib.parse import urlparse, parse_qs

    parsed = urlparse(uri)
    scheme = parsed.scheme.lower()

    if scheme in ("sqlite", "sqlite3"):
        path = parsed.path or ":memory:"
        # sqlite:///:memory: → urlparse gives "/:memory:", normalize it
        if path == "/:memory:":
            path = ":memory:"
        return SQLiteStore(path)

    if scheme in ("postgresql", "postgres"):
        return PostgreSQLStore(uri)

    if scheme in ("mongodb", "mongodb+srv"):
        db_name = parsed.path.lstrip("/") or "clawid"
        base_uri = f"{parsed.scheme}://{parsed.netloc}"
        return MongoDBStore(base_uri, db_name=db_name)

    if scheme == "redis" or scheme == "rediss":
        qs = parse_qs(parsed.query)
        ttl = int(qs["ttl"][0]) if "ttl" in qs else None
        clean_uri = uri.split("?")[0]
        return RedisStore(clean_uri, ttl=ttl)

    raise ValueError(
        f"Unsupported store URI scheme: '{scheme}'\n"
        "Supported: sqlite, postgresql, mongodb, redis"
    )


__all__ = [
    "ClawIDStore",
    "SQLiteStore",
    "PostgreSQLStore",
    "MongoDBStore",
    "RedisStore",
    "from_uri",
]
