"""
Schema Retriever — loads BigQuery table function metadata and returns
the most relevant functions for a given question.
"""

import json
from pathlib import Path

SCHEMA_FILE = Path(__file__).parent / "schema.json"


class SchemaRetriever:
    def __init__(self):
        self.schema = self._load_schema()

    def _load_schema(self) -> list:
        if not SCHEMA_FILE.exists():
            print(f"  [Warning] schema.json not found at {SCHEMA_FILE}")
            return []
        with open(SCHEMA_FILE) as f:
            return json.load(f)

    def get_relevant_schema(self, question: str) -> str:
        if not self.schema:
            return "No schema loaded."

        question_lower = question.lower()
        scored = []

        for func in self.schema:
            score = 0
            name        = func.get("function_name", "").lower()
            description = func.get("description", "").lower()
            tags        = [t.lower() for t in func.get("tags", [])]
            columns     = func.get("columns", [])

            for word in question_lower.split():
                if len(word) < 3:
                    continue
                if word in name:        score += 3
                if word in description: score += 2
                if any(word in tag for tag in tags): score += 2
                for col in columns:
                    if word in col.get("name", "").lower():        score += 1
                    if word in col.get("description", "").lower(): score += 1

            if score > 0:
                scored.append((score, func))

        scored.sort(key=lambda x: x[0], reverse=True)
        top = [f for _, f in scored[:5]] or self.schema[:5]

        return self._format_schema(top)

    def _format_schema(self, functions: list) -> str:
        lines = []
        for fn in functions:
            name        = fn.get("function_name", "unknown")
            description = fn.get("description", "")
            call_syntax = fn.get("call_syntax", "")
            params      = fn.get("parameters", [])
            partition   = fn.get("partition_column", None)

            lines.append(f"TABLE FUNCTION: `{name}`")
            if description:
                lines.append(f"  Description: {description}")
            if call_syntax:
                lines.append(f"  Call syntax: {call_syntax}")
            if partition:
                lines.append(f"  Partition/date filter column: {partition}")

            if params:
                lines.append("  Parameters:")
                for p in params:
                    lines.append(
                        f"    - {p['name']} ({p['type']}): {p.get('description','')}"
                    )

            lines.append("  Columns:")
            for col in fn.get("columns", []):
                col_line = f"    - {col['name']} ({col['type']})"
                if col.get("description"):
                    col_line += f": {col['description']}"
                if col.get("example"):
                    col_line += f" [e.g. {col['example']}]"
                lines.append(col_line)

            lines.append("")

        return "\n".join(lines)
