import os
import json
from pathlib import Path
from app.config import get_settings

settings = get_settings()
PERMISSIONS_FILE = os.path.join(settings.PERMISSIONS_DIR, "docs_permissions.json")


def load_permissions() -> dict:
    if os.path.exists(PERMISSIONS_FILE):
        with open(PERMISSIONS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {}


def save_permissions(perms: dict):
    os.makedirs(settings.PERMISSIONS_DIR, exist_ok=True)
    with open(PERMISSIONS_FILE, "w", encoding="utf-8") as f:
        json.dump(perms, f, indent=2, ensure_ascii=False)


def discover_docs() -> dict:
    docs_dir = settings.DOCS_DIR
    if not os.path.exists(docs_dir):
        return {}
    perms = load_permissions()
    existing_slugs = set(perms.keys())
    for filename in os.listdir(docs_dir):
        if filename.endswith(".md"):
            slug = Path(filename).stem
            if slug not in existing_slugs:
                title = slug.replace("-", " ").title()
                perms[slug] = {
                    "title": title,
                    "filename": filename,
                    "sort_order": len(perms),
                    "permissions": {
                        "engineer": {"view": False, "edit": False, "cancel": False},
                        "technician": {"view": False},
                    },
                }
    # migrate existing entries missing technician key
    changed = False
    for slug, doc in perms.items():
        if "permissions" not in doc:
            doc["permissions"] = {}
        perms_doc = doc["permissions"]
        if "technician" not in perms_doc:
            perms_doc["technician"] = {"view": False}
            changed = True
        # ensure engineer has edit/cancel defaults
        eng = perms_doc.setdefault("engineer", {})
        if "edit" not in eng:
            eng["edit"] = False
            changed = True
        if "cancel" not in eng:
            eng["cancel"] = False
            changed = True
    if changed:
        save_permissions(perms)
    return perms


def get_allowed_docs(role: str) -> list[dict]:
    perms = discover_docs()
    if role == "owner":
        return sorted(perms.values(), key=lambda x: x.get("sort_order", 0))
    if role == "engineer":
        return [
            doc for doc in perms.values()
            if doc.get("permissions", {}).get("engineer", {}).get("view", False)
        ]
    if role == "technician":
        return [
            doc for doc in perms.values()
            if doc.get("permissions", {}).get("technician", {}).get("view", False)
        ]
    return []


def can_access_doc(role: str, slug: str, action: str = "view") -> bool:
    if role == "owner":
        return True
    perms = load_permissions()
    doc = perms.get(slug, {})
    if role == "engineer":
        return doc.get("permissions", {}).get("engineer", {}).get(action, False)
    if role == "technician":
        return doc.get("permissions", {}).get("technician", {}).get("view", False)
    return False
