"""MCP tool definitions for Prompt Forge."""
from __future__ import annotations

import json
import os
from pathlib import Path

DEFAULT_TOOLS = [
    {
        "name": "promptforge.secure_generate",
        "description": "Send a request through the Prompt Forge secure gateway.",
        "input_schema": {
            "type": "object",
            "required": ["provider", "model", "messages"],
            "properties": {
                "provider": {"type": "string"},
                "model": {"type": "string"},
                "messages": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "required": ["role", "content"],
                        "properties": {
                            "role": {"type": "string"},
                            "content": {"type": "string"},
                        },
                    },
                },
                "temperature": {"type": "number"},
                "top_p": {"type": "number"},
                "frequency_penalty": {"type": "number"},
                "presence_penalty": {"type": "number"},
                "stop": {"oneOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}}]},
                "max_tokens": {"type": "integer"},
                "stream": {"type": "boolean"},
                "tools": {"type": "array", "items": {"type": "object"}},
                "tool_choice": {"oneOf": [{"type": "string"}, {"type": "object"}]},
                "user": {"type": "string"},
                "use_case": {"type": "string"},
                "metadata": {"type": "object"},
                "trace_id": {"type": "string", "format": "uuid"},
                "policy_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "required": ["id", "provider", "model"],
            "properties": {
                "id": {"type": "string", "format": "uuid"},
                "provider": {"type": "string"},
                "model": {"type": "string"},
                "output_text": {"type": "string"},
                "choices": {"type": "array", "items": {"type": "object"}},
                "usage": {"type": "object"},
                "latency_ms": {"type": "integer"},
                "cost_usd": {"type": "number"},
                "security": {"type": "object"},
                "trace_id": {"type": "string", "format": "uuid"},
                "request_id": {"type": "string"},
            },
        },
    },
    {
        "name": "promptforge.redact_and_tokenize",
        "description": "Tokenize sensitive entities using Secure Mode.",
        "input_schema": {
            "type": "object",
            "required": ["text"],
            "properties": {
                "text": {"type": "string"},
                "entity_labels": {"type": "array", "items": {"type": "string"}},
                "entity_types": {"type": "array", "items": {"type": "string"}},
                "fail_closed": {"type": "boolean"},
                "debug_sources": {"type": "boolean"},
                "metadata": {"type": "object"},
                "org_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "required": ["tokenized_text", "token_vault_id", "entity_counts"],
            "properties": {
                "tokenized_text": {"type": "string"},
                "token_vault_id": {"type": "string", "format": "uuid"},
                "entity_counts": {"type": "object"},
                "detection_sources": {"type": "object"},
            },
        },
    },
    {
        "name": "promptforge.policy_dry_run",
        "description": "Evaluate an egress policy decision without executing a provider call.",
        "input_schema": {
            "type": "object",
            "required": ["provider", "model"],
            "properties": {
                "provider": {"type": "string"},
                "model": {"type": "string"},
                "region": {"type": "string"},
                "policy_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "required": ["allowed", "fail_closed"],
            "properties": {
                "allowed": {"type": "boolean"},
                "reason": {"type": "string"},
                "policy_id": {"type": "string", "format": "uuid"},
                "rule_ids": {"type": "array", "items": {"type": "string"}},
                "fail_closed": {"type": "boolean"},
                "retention_days": {"type": "integer"},
            },
        },
    },
    {
        "name": "promptforge.audit_query",
        "description": "Query audit logs (admin-only).",
        "input_schema": {
            "type": "object",
            "properties": {
                "org_id": {"type": "string", "format": "uuid"},
                "start_date": {"type": "string", "format": "date-time"},
                "end_date": {"type": "string", "format": "date-time"},
                "action": {"type": "string"},
                "user_id": {"type": "string", "format": "uuid"},
                "limit": {"type": "integer"},
                "cursor": {"type": "string"},
            },
        },
        "output_schema": {
            "type": "object",
            "properties": {
                "logs": {"type": "array", "items": {"type": "object"}},
                "next_cursor": {"type": "string"},
            },
        },
    },
    {
        "name": "promptforge.detokenize",
        "description": "Detokenize content with an authorized token vault reference.",
        "input_schema": {
            "type": "object",
            "required": ["token_vault_id", "text"],
            "properties": {
                "token_vault_id": {"type": "string", "format": "uuid"},
                "text": {"type": "string"},
                "org_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "required": ["text"],
            "properties": {
                "text": {"type": "string"},
            },
        },
    },
    {
        "name": "promptforge.list_gateway_requests",
        "description": "List gateway request logs for an organization (metadata only, no raw prompt content).",
        "input_schema": {
            "type": "object",
            "required": ["org_id"],
            "properties": {
                "org_id": {"type": "string", "format": "uuid"},
                "start_date": {"type": "string", "format": "date-time"},
                "end_date": {"type": "string", "format": "date-time"},
                "provider": {"type": "string"},
                "decision": {"type": "string", "enum": ["allow", "deny", "redact"]},
                "limit": {"type": "integer", "default": 50, "maximum": 100},
                "cursor": {"type": "string"},
            },
        },
        "output_schema": {
            "type": "object",
            "properties": {
                "logs": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "id": {"type": "string", "format": "uuid"},
                            "created_at": {"type": "string"},
                            "provider": {"type": "string"},
                            "model": {"type": "string"},
                            "use_case": {"type": "string"},
                            "decision": {"type": "string"},
                            "redaction_applied": {"type": "boolean"},
                            "entity_counts": {"type": "object"},
                            "threat_flags": {"type": "array", "items": {"type": "string"}},
                            "latency_ms": {"type": "integer"},
                            "cost_usd": {"type": "number"},
                            "error_code": {"type": "string"},
                        },
                    },
                },
                "next_cursor": {"type": "string"},
            },
        },
    },
    {
        "name": "promptforge.list_secure_mode_entities",
        "description": "List all available Secure Mode entity types valid for entity_types and entity_labels fields.",
        "input_schema": {
            "type": "object",
            "properties": {},
        },
        "output_schema": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["id", "name", "description"],
                "properties": {
                    "id": {"type": "string"},
                    "name": {"type": "string"},
                    "description": {"type": "string"},
                },
            },
        },
    },
    {
        "name": "promptforge.get_secure_mode_config",
        "description": "Get the current Secure Mode configuration for an organization.",
        "input_schema": {
            "type": "object",
            "required": ["org_id"],
            "properties": {
                "org_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "properties": {
                "enabled": {"type": "boolean"},
                "entity_labels": {"type": "array", "items": {"type": "string"}},
                "entity_types": {"type": "array", "items": {"type": "string"}},
                "threshold": {"type": "number"},
                "fail_closed": {"type": "boolean"},
                "allowed_providers": {"type": "array", "items": {"type": "string"}},
                "allowed_regions": {"type": "array", "items": {"type": "string"}},
            },
        },
    },
    {
        "name": "promptforge.get_billing_status",
        "description": "Get billing status and usage metrics for an organization.",
        "input_schema": {
            "type": "object",
            "required": ["org_id"],
            "properties": {
                "org_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "properties": {
                "plan": {"type": "string"},
                "status": {"type": "string"},
                "current_period_end": {"type": "string"},
                "usage": {"type": "object"},
                "payment_method": {"type": "object"},
            },
        },
    },
    {
        "name": "promptforge.list_billing_plans",
        "description": "List all available billing plans with pricing, request limits, and feature sets.",
        "input_schema": {
            "type": "object",
            "properties": {},
        },
        "output_schema": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": {"type": "string"},
                    "name": {"type": "string"},
                    "price_monthly": {"type": "integer"},
                    "requests_limit": {"type": "integer"},
                    "sort_order": {"type": "integer"},
                    "features": {"type": "array", "items": {"type": "string"}},
                    "contact_url": {"type": "string"},
                },
            },
        },
    },
    {
        "name": "promptforge.list_providers",
        "description": "List configured LLM providers for an organization.",
        "input_schema": {
            "type": "object",
            "required": ["org_id"],
            "properties": {
                "org_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": {"type": "string", "format": "uuid"},
                    "provider_type": {"type": "string"},
                    "name": {"type": "string"},
                    "is_enabled": {"type": "boolean"},
                    "allowed_models": {"type": "array", "items": {"type": "string"}},
                    "allowed_regions": {"type": "array", "items": {"type": "string"}},
                    "has_credentials": {"type": "boolean"},
                    "last_validated_at": {"type": "string"},
                    "created_at": {"type": "string"},
                },
            },
        },
    },
    {
        "name": "promptforge.test_provider",
        "description": "Test a provider connection and validate its credentials.",
        "input_schema": {
            "type": "object",
            "required": ["provider_id"],
            "properties": {
                "provider_id": {"type": "string", "format": "uuid"},
            },
        },
        "output_schema": {
            "type": "object",
            "required": ["success", "message"],
            "properties": {
                "success": {"type": "boolean"},
                "message": {"type": "string"},
                "latency_ms": {"type": "integer"},
            },
        },
    },
]


def load_tools() -> list[dict]:
    """Load tool definitions from disk if available."""
    override = os.getenv("PROMPTFORGE_MCP_TOOLS_PATH")
    if override and Path(override).exists():
        with open(override, "r", encoding="utf-8") as handle:
            data = json.load(handle)
            return data.get("tools", DEFAULT_TOOLS)

    candidate = Path(__file__).resolve().parents[2] / "promptforge-schemas" / "mcp" / "tools.v1.json"
    if candidate.exists():
        with open(candidate, "r", encoding="utf-8") as handle:
            data = json.load(handle)
            return data.get("tools", DEFAULT_TOOLS)

    return DEFAULT_TOOLS
