from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from keepedu_performance.core.config import settings
from keepedu_performance.core.layout import (
    REPO_ROOT,
    SOURCE_DIR as PACKAGE_SOURCE_DIR,
    resolve_from,
)


SOURCE_DIR = PACKAGE_SOURCE_DIR


@dataclass(frozen=True)
class PipelinePaths:
    runtime_root: Path
    tenant_root: Path | None
    raw: Path
    xampp_db_raw: Path
    bronze: Path
    silver: Path
    gold: Path
    audit: Path
    export: Path
    log: Path
    external: Path
    dimensions: Path


def build_pipeline_paths(
    configuration=settings, repo_root: Path = REPO_ROOT
) -> PipelinePaths:
    runtime_root = resolve_from(
        repo_root,
        configuration.keepedu_runtime_root or ".",
    )

    tenant_root = None
    if configuration.pipeline_tenant_id:
        tenant_root = (
            resolve_from(runtime_root, configuration.tenant_data_path)
            / configuration.pipeline_tenant_id
            / str(configuration.keepedu_anoletivo)
        )

    def stage_path(configured_path: str, tenant_stage: str) -> Path:
        if tenant_root is not None:
            return tenant_root / tenant_stage
        return resolve_from(runtime_root, configured_path)

    raw = stage_path(configuration.raw_path, "raw")
    return PipelinePaths(
        runtime_root=runtime_root,
        tenant_root=tenant_root,
        raw=raw,
        xampp_db_raw=raw / "xampp_db",
        bronze=stage_path(configuration.bronze_path, "bronze"),
        silver=stage_path(configuration.silver_path, "silver"),
        gold=stage_path(configuration.gold_path, "gold"),
        audit=stage_path(configuration.audit_path, "audit"),
        export=stage_path(configuration.export_path, "exports"),
        log=stage_path(configuration.log_path, "logs"),
        external=stage_path(configuration.external_path, "external"),
        dimensions=stage_path(configuration.dimensions_path, "dimensions"),
    )


PATHS = build_pipeline_paths()

# BASE_DIR is retained as a compatibility alias for the repository/project root.
# Runtime data belongs under RUNTIME_ROOT and package code belongs under SOURCE_DIR.
BASE_DIR = REPO_ROOT
RUNTIME_ROOT = PATHS.runtime_root
TENANT_ROOT = PATHS.tenant_root

RAW_DIR = PATHS.raw
XAMPP_DB_RAW_DIR = PATHS.xampp_db_raw
BRONZE_DIR = PATHS.bronze
SILVER_DIR = PATHS.silver
GOLD_DIR = PATHS.gold
AUDIT_DIR = PATHS.audit
EXPORT_DIR = PATHS.export
LOG_DIR = PATHS.log
EXTERNAL_DIR = PATHS.external
DIMENSIONS_DIR = PATHS.dimensions


def ensure_directories() -> None:
    for path in [
        RAW_DIR,
        XAMPP_DB_RAW_DIR,
        BRONZE_DIR,
        SILVER_DIR,
        GOLD_DIR,
        AUDIT_DIR,
        EXPORT_DIR,
        LOG_DIR,
        EXTERNAL_DIR,
        DIMENSIONS_DIR,
    ]:
        path.mkdir(parents=True, exist_ok=True)
