"""Slim tool: discover_model — Discover schema and infer relationships."""
import json
from typing import Any, Optional


def discover_model(
    connection_id: Optional[str] = None,
    database: Optional[str] = None,
    schema_name: Optional[str] = None,
    tables: str = "",
) -> str:
    """Discover database schema and infer relationships between tables.

    Args:
        connection_id: Optional connection ID for backend database.
        database: Optional database name.
        schema_name: Optional schema name.
        tables: Optional comma-separated table names to analyze.

    Returns:
        JSON with discovered schema, inferred relationships, and model recommendations.
    """
    from databridge.modeling import discover, infer_relationships

    table_list = [t.strip() for t in tables.split(",") if t.strip()] if tables else None
    result: dict[str, Any] = {}

    result["schema"] = discover(
        connection_id=connection_id,
        database=database,
        schema_name=schema_name,
        tables=table_list,
    )

    if table_list and len(table_list) >= 2:
        result["relationships"] = infer_relationships(
            tables=table_list,
            connection_id=connection_id,
            database=database,
            schema_name=schema_name,
        )

    return json.dumps(result, indent=2, default=str)
