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",
}

MIN_RELEASE_GATES_TEMPLATE = {
    "version": "1.0.0",
    "runtime_mode": "ai_filter",
    "promotion_flow": ["shadow", "paper", "canary_10pct", "full"],
    "promotion_gates": {
        "shadow_to_paper": {
            "min_shadow_signals": 300,
            "max_schema_validation_error_rate_pct": 0.5,
        },
        "paper_to_canary_10pct": {
            "min_paper_trades": 0,
            "max_drawdown_pct": 3.0,
            "min_profit_factor": 1.15,
        },
        "canary_10pct_to_full": {
            "min_canary_trades": 80,
            "max_reject_rate_pct": 8.0,
            "max_p95_e2e_latency_ms": 1800,
        },
    },
    "rollback_triggers": [],
}

MIN_RUNTIME_STATE_TEMPLATE = {
    "pending_auto_actions": [],
    "last_auto_actions_emitted_at": "",
}


def _fallback_template(rel: str) -> dict:
    if rel.endswith("ops/release_gates.json"):
        return dict(MIN_RELEASE_GATES_TEMPLATE)
    if rel.endswith("ops/runtime_state.json"):
        return dict(MIN_RUNTIME_STATE_TEMPLATE)
    return {}


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(json.dumps(_fallback_template(rel), ensure_ascii=False, indent=2), 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"]
