"""User-owned OPA/Rego policy directory for pip-installed ACP."""

from __future__ import annotations

import os
import shutil
from pathlib import Path

from importlib.resources import as_file, files

from acp.runtime import acp_home

HOW_TO_ADD_RULES = """# How to add your own governance rules

Your policies live in this folder. OPA and the dashboard both read these `.rego` files.

## Starter layout

| File | Purpose |
|------|---------|
| `router.rego` | Routes `input.tool` to policy bundles |
| `rbac.rego` | JWT roles → tool access |
| `mortgage_application.rego` | Commented sample — loan submission |
| `mortgage_underwriting.rego` | Commented sample — score_loan / escalate |

No demo rules (refund, fraud, etc.) are included — add your own domains.

## Enable mortgage samples

1. Uncomment rules in `mortgage_application.rego` or `mortgage_underwriting.rego`
2. Uncomment the matching `import` and `decision` blocks in `router.rego`
3. Uncomment tool → role entries in `rbac.rego` (e.g. `"los_api": ["origination"]`)
4. Restart: `acp down && acp up`
5. Check dashboard **Policies** tab

## Add a new tool (any domain)

1. Create `my_tool.rego` with `package acp.my_tool` and decision rules
2. Add import + route in `router.rego`
3. Add tool → roles in `rbac.rego`
4. Mint a dev JWT with the matching role (roles claim)
5. Restart stack and call via `@governed_tool` or `POST /tool-call`

## Test (optional)

```bash
opa test .
```

Requires [OPA CLI](https://www.openpolicyagent.org/docs/latest/#running-opa) installed.
"""


def policies_dir() -> Path:
    """Writable policy directory (default ~/.acp/policies)."""
    raw = os.environ.get("ACP_POLICIES_DIR", "").strip()
    if raw:
        return Path(raw).expanduser().resolve()
    return (acp_home() / "policies").resolve()


def _starter_policies_dir() -> Path:
    with as_file(files("acp").joinpath("policy-starter")) as src:
        return Path(src)


def init_policies(*, force: bool = False) -> Path:
    """Create user policy folder with minimal starter Rego (no demo bundles)."""
    dest = policies_dir()
    dest.mkdir(parents=True, exist_ok=True)
    src = _starter_policies_dir()

    for item in sorted(src.iterdir()):
        if not item.is_file() or item.suffix != ".rego":
            continue
        target = dest / item.name
        if target.exists() and not force:
            continue
        shutil.copy2(item, target)

    how_to = dest / "HOW_TO_ADD_RULES.md"
    if force or not how_to.exists():
        how_to.write_text(HOW_TO_ADD_RULES, encoding="utf-8")

    return dest


def ensure_policies_ready() -> Path:
    """Ensure policy dir exists; auto-init on first `acp up` if empty."""
    dest = policies_dir()
    has_rego = dest.is_dir() and any(dest.glob("*.rego"))
    if not has_rego:
        print(f"No policies in {dest} — running acp init…")
        init_policies()
    return dest


def policies_status_lines() -> list[str]:
    dest = policies_dir()
    count = len(list(dest.glob("*.rego"))) if dest.is_dir() else 0
    return [
        f"Policies dir: {dest}",
        f"Rego files:   {count}",
    ]
