"""stock_screener tool — premium stock screening with license gating."""

from __future__ import annotations

import json
from typing import Any

from finagent_pro.license import require_license
from finagent_pro.services.screener import ScreenerService

_service = ScreenerService()


def stock_screener(
    filters: dict[str, Any],
    sort_by: str | None = None,
    limit: int = 20,
) -> str:
    """Screen stocks by financial criteria.

    PRO FEATURE — requires a FinAgent Pro license key.
    """
    gate = require_license("stock_screener")
    if gate is not None:
        return gate

    try:
        results = _service.screen(filters=filters, sort_by=sort_by, limit=limit)
    except Exception as exc:
        return json.dumps({"error": "service_error", "message": str(exc)})

    return json.dumps(results, default=str)
