from pocket_analyst._session import _Session
from pocket_analyst._db import connection, schema


def explore_schema(session: _Session) -> str:
    engine = connection.get_engine(session)
    return schema.explore_schema(engine, user_context=connection.get_context(session))


def describe_table(table_name: str, session: _Session) -> str:
    engine = connection.get_engine(session)
    info = schema.describe_table(engine, table_name)
    lines = [f"Table: {info['table']}", f"Rows: {info['row_count']:,}", "", "Columns:"]
    for col in info["columns"]:
        pk_flag = " [PK]" if col["primary_key"] else ""
        null_flag = "" if col["nullable"] else " NOT NULL"
        samples_str = ", ".join(str(s) for s in col["samples"]) if col["samples"] else "—"
        lines.append(f"  {col['name']}{pk_flag}  {col['type']}{null_flag}")
        stat_parts = []
        if col.get("null_rate") is not None and col["null_rate"] > 0:
            stat_parts.append(f"{col['null_rate']:.0%} null")
        if col.get("distinct_count") is not None:
            stat_parts.append(f"{col['distinct_count']:,} distinct")
        stat_str = " | ".join(stat_parts)
        lines.append(f"    {stat_str + ' | ' if stat_str else ''}samples: {samples_str}")
    if info["foreign_keys"]:
        lines.append("\nForeign keys:")
        for fk in info["foreign_keys"]:
            lines.append(f"  {fk['column']} → {fk['references']}")
    return "\n".join(lines)
