"""Tenant and app storage routing."""

from __future__ import annotations

from pathlib import Path
from typing import Any


class StorageRouter:
    """Resolve per-tenant, per-app filesystem locations."""

    def __init__(self, base_path: str | Path | None = None) -> None:
        self.base_path = Path(base_path or "/var/www/html/flask_server/storage/tenants")

    def get_tenant_storage_root(self, tenant_id: str, app_id: str) -> Path:
        """Return the storage root for the given tenant and app."""
        tenant_key = (tenant_id or "").strip()
        app_key = (app_id or "").strip()
        return self.base_path / tenant_key / app_key

    def resolve(self, *, tenant: dict[str, Any] | None, app_id: str | None) -> dict[str, Any]:
        tenant_id = (tenant or {}).get("storage_key") or (tenant or {}).get("slug") or (tenant or {}).get("tenant_id")
        path = self.get_tenant_storage_root(tenant_id or "unknown", app_id or "unknown")
        return {
            "tenant_id": tenant_id,
            "app_id": app_id,
            "root": str(path),
        }

