"""
DataVault Plugin Runner — Pro Tier Only
========================================
Allows Pro nodes to:
    - Install and register plugins
    - Run plugins to generate reports
    - Publish reports with pricing
    - Generate all reports in batch

This module is NOT included in the Basic package.
"""

import os
import json
import logging
import requests
from typing import Dict, List, Optional, Any

logger = logging.getLogger("biznode.datavault.runner")

_DASHBOARD_URL = os.getenv("DASHBOARD_URL", "http://localhost:7777")
_API_BASE = f"{_DASHBOARD_URL}/api/datavault"


def _headers() -> Dict[str, str]:
    secret = os.getenv("BOT_SECRET", "")
    return {"X-Bot-Secret": secret, "Content-Type": "application/json"}


def _check_pro_tier() -> bool:
    """Verify Pro tier before allowing generation."""
    try:
        from services.tier_manager import is_feature_allowed
        return is_feature_allowed("datavault_generate")
    except ImportError:
        return False


def generate_report(
    command: str,
    args: str = "",
    price: float = 0.0,
    currency: str = "BZeUSD",
    access_tier: str = "BASIC",
    creator_node: str = "",
) -> Dict[str, Any]:
    """
    Generate a report via the Dashboard API.
    Requires Pro tier.
    """
    if not _check_pro_tier():
        return {"success": False, "message": "Report generation requires Pro license."}

    try:
        payload = {
            "command": command,
            "args": args,
            "price": price,
            "currency": currency,
            "access_tier": access_tier,
            "creator_node": creator_node,
        }
        r = requests.post(
            f"{_API_BASE}/reports/generate",
            json=payload,
            headers=_headers(),
            timeout=60,
        )
        r.raise_for_status()
        return r.json()
    except requests.HTTPError as e:
        detail = ""
        try:
            detail = e.response.json().get("detail", "")
        except Exception:
            pass
        return {"success": False, "message": detail or str(e)}
    except Exception as e:
        logger.error(f"Failed to generate report: {e}")
        return {"success": False, "message": str(e)}


def generate_all_reports(
    plugin_id: str = "aisalesteam",
    price: float = 0.0,
    creator_node: str = "",
) -> Dict[str, Any]:
    """Generate all reports for a plugin in batch."""
    if not _check_pro_tier():
        return {"success": False, "message": "Report generation requires Pro license."}

    # Get plugin commands via API
    try:
        r = requests.get(f"{_API_BASE}/commands", headers=_headers(), timeout=10)
        r.raise_for_status()
        commands = r.json().get("commands", [])
    except Exception as e:
        return {"success": False, "message": f"Failed to fetch commands: {e}"}

    # Filter to this plugin
    plugin_cmds = [c for c in commands if c.get("plugin_id") == plugin_id]
    if not plugin_cmds:
        return {"success": False, "message": f"No commands found for plugin: {plugin_id}"}

    results = {"success": True, "generated": 0, "failed": 0, "reports": []}
    for cmd in plugin_cmds:
        result = generate_report(
            command=cmd["command"],
            price=price,
            creator_node=creator_node,
        )
        if result.get("success"):
            results["generated"] += 1
            results["reports"].append({
                "command": cmd["command"],
                "report_id": result.get("report_id"),
                "title": result.get("title"),
            })
        else:
            results["failed"] += 1

    results["message"] = f"Generated {results['generated']}, failed {results['failed']}"
    return results


def register_plugin(plugin_path: str) -> Dict[str, Any]:
    """
    Register a new plugin from a local directory.
    Requires plugin.json in the directory.
    """
    if not _check_pro_tier():
        return {"success": False, "message": "Plugin registration requires Pro license."}

    manifest_path = os.path.join(plugin_path, "plugin.json")
    if not os.path.isfile(manifest_path):
        return {
            "success": False,
            "message": f"plugin.json not found in {plugin_path}. "
                       "Create a plugin.json with: name, description, version, commands[], entry_point",
        }

    try:
        with open(manifest_path, "r", encoding="utf-8") as f:
            manifest = json.load(f)
        manifest["plugin_path"] = os.path.abspath(plugin_path)
        logger.info(f"Plugin registered: {manifest.get('name', 'unknown')}")
        return {"success": True, "plugin": manifest}
    except Exception as e:
        return {"success": False, "message": f"Failed to read plugin.json: {e}"}
