"""obol policies - manage access policies."""
from obol.cli._base import get_api, handle_api_error, output, table, add_format_arg


POLICY_TEMPLATES = {
    "strict-files": {
        "description": "Block file access below trusted tier",
        "resource": "file:*",
        "min_trust": 70,
        "min_tier": "trusted",
        "action": "block",
    },
    "credential-gate": {
        "description": "Only privileged agents can access credentials",
        "resource": "credentials.*",
        "min_trust": 90,
        "min_tier": "privileged",
        "action": "block",
    },
    "network-monitor": {
        "description": "Log all network access, warn on low trust",
        "resource": "network:*",
        "min_trust": 30,
        "min_tier": "probationary",
        "action": "warn",
    },
    "database-protect": {
        "description": "Block database writes for untrusted agents",
        "resource": "database:write:*",
        "min_trust": 60,
        "min_tier": "trusted",
        "action": "block",
    },
    "sensitive-data": {
        "description": "Gate access to PII and sensitive data",
        "resource": "data:pii:*",
        "min_trust": 85,
        "min_tier": "privileged",
        "action": "block",
    },
}


@handle_api_error
def cmd_policies(args):
    fmt = getattr(args, "format", "text")
    sub = getattr(args, "policies_cmd", None)

    # Templates is local-only, no API key needed
    if sub == "templates":
        if fmt == "json":
            output(POLICY_TEMPLATES, fmt="json")
            return

        print("Available Policy Templates:")
        print()
        for name, tmpl in POLICY_TEMPLATES.items():
            print(f"  {name}")
            print(f"    {tmpl['description']}")
            print(f"    Resource:  {tmpl['resource']}")
            print(f"    Min Trust: {tmpl['min_trust']}")
            print(f"    Min Tier:  {tmpl['min_tier']}")
            print(f"    Action:    {tmpl['action']}")
            print()
        print("Apply with: obol policies create --resource <res> --min-trust <N> --min-tier <tier> --action <act>")
        return

    api = get_api()

    if sub == "create":
        result = api.create_policy(
            resource=args.resource,
            min_trust=args.min_trust,
            min_tier=args.min_tier,
            action=args.action,
        )
        if fmt == "json":
            output(result, fmt="json")
        else:
            print(f"Policy #{result['id']} created: {result['resource']}")
        return

    if sub == "delete":
        # Delete via API - would need a delete endpoint
        print(f"Policy deletion not yet supported via CLI. Use the dashboard.")
        return

    # Default: list
    data = api.list_policies()

    if fmt == "json":
        output(data, fmt="json")
        return

    policies = data.get("policies", [])
    if not policies:
        print("No policies configured.")
        print("Run: obol policies templates (for examples)")
        return

    rows = []
    for p in policies:
        rows.append([
            p["id"],
            p["resource"],
            p["min_trust"],
            p["min_tier"],
            p["action"],
        ])

    table(
        ["ID", "Resource", "Min Trust", "Min Tier", "Action"],
        rows,
        max_widths={1: 40},
    )


def setup_parser(subparsers):
    """Add policies subparser."""
    parser = subparsers.add_parser("policies", help="Access policies")
    parser.set_defaults(func=cmd_policies, policies_cmd=None)
    add_format_arg(parser)

    sub = parser.add_subparsers(dest="policies_cmd")

    sub.add_parser("list", help="List policies")
    sub.add_parser("templates", help="Show policy templates")

    create = sub.add_parser("create", help="Create a policy")
    create.add_argument("--resource", required=True, help="Resource pattern")
    create.add_argument("--min-trust", type=float, default=50, help="Minimum trust score")
    create.add_argument("--min-tier", default="trusted",
                        choices=["untrusted", "probationary", "trusted", "privileged"])
    create.add_argument("--action", default="block", choices=["block", "warn", "log"])

    delete = sub.add_parser("delete", help="Delete a policy")
    delete.add_argument("policy_id", type=int)
