from __future__ import annotations

import json

from agents import function_tool
from click.testing import CliRunner


try:
    from screener_cli.cli import main as screener_main
except Exception:  # pragma: no cover
    screener_main = None


_screener_runner = CliRunner() if screener_main is not None else None


@function_tool
def screener_get_data(symbol: str, section: str, view: str = "consolidated") -> str:
    """Fetch financial data for an Indian stock from screener.in."""
    if _screener_runner is None or screener_main is None:
        return json.dumps(
            {
                "error": (
                    "screener_cli is not installed. Install a compatible package that exposes "
                    "screener_cli.cli:main to enable screener_get_data."
                )
            }
        )

    result = _screener_runner.invoke(screener_main, ["--view", view, symbol, section])
    if result.exit_code != 0:
        return json.dumps({"error": result.output.strip()})
    return result.output.strip()
