import json
from pathlib import Path
from typing import Dict, List


TENANT_FILES = {
    "config/risk_governor_rules.json": "config/risk_governor_rules.json",
    "ops/release_gates.json": "ops/release_gates.json",
    "ops/runtime_state.json": "ops/runtime_state.json",
}


def ensure_tenant_workspace(project_root: Path, tenant_id: str) -> Path:
    tenant_dir = project_root / "tenants" / tenant_id
    for rel, base_rel in TENANT_FILES.items():
        dst = tenant_dir / rel
        if dst.exists():
            continue
        src = project_root / base_rel
        dst.parent.mkdir(parents=True, exist_ok=True)
        if src.exists():
            dst.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
        else:
            dst.write_text("{}", encoding="utf-8")
    return tenant_dir


def tenant_paths(project_root: Path, tenant_id: str) -> Dict[str, Path]:
    if not tenant_id:
        return {
            "risk": project_root / "config/risk_governor_rules.json",
            "release": project_root / "ops/release_gates.json",
            "runtime": project_root / "ops/runtime_state.json",
            "audit": project_root / "logs/chat_tuning_audit.ndjson",
        }
    tenant_dir = ensure_tenant_workspace(project_root, tenant_id)
    return {
        "risk": tenant_dir / "config/risk_governor_rules.json",
        "release": tenant_dir / "ops/release_gates.json",
        "runtime": tenant_dir / "ops/runtime_state.json",
        "audit": tenant_dir / "logs/chat_tuning_audit.ndjson",
    }


def load_runtime_state(project_root: Path, tenant_id: str) -> Dict[str, object]:
    paths = tenant_paths(project_root, tenant_id)
    runtime_path = paths["runtime"]
    if not runtime_path.exists():
        return {}
    try:
        return json.loads(runtime_path.read_text(encoding="utf-8"))
    except Exception:
        return {}


def list_tenants(project_root: Path) -> List[str]:
    tenants_dir = project_root / "tenants"
    if not tenants_dir.exists():
        return []
    return sorted([p.name for p in tenants_dir.iterdir() if p.is_dir()])


def get_audit_path(project_root: Path, tenant_id: str) -> Path:
    return tenant_paths(project_root, tenant_id)["audit"]
