# Generated by GitHub Copilot
"""
Semantic View Dependency Parser

Extracts table dependencies from semantic view YAML definitions.
Semantic views depend on tables defined in the 'tables.base_table' sections of the YAML.
"""

import re
import yaml
from typing import List, Set, Tuple


class SemanticViewDependencyParser:
    """
    Parses semantic view YAML files to extract table dependencies.
    """

    @staticmethod
    def extract_table_dependencies(yaml_content: str) -> Set[str]:
        """
        Extract fully-qualified table names from semantic view YAML.
        
        Looks for patterns like:
        tables:
          base_table:
            database: DB_NAME
            schema: SCHEMA_NAME
            table: TABLE_NAME
        
        Returns a set of fully-qualified table names in format: DATABASE.SCHEMA.TABLE
        
        Args:
            yaml_content: The YAML content of a semantic view definition
            
        Returns:
            Set of fully-qualified table names (uppercase)

        Raises:
            ValueError: If the YAML content cannot be parsed or dependencies cannot
                be extracted. The pipeline must fail fast on malformed semantic view
                definitions rather than silently continuing without dependencies.
        """
        dependencies = set()
        
        try:
            # Parse the YAML content
            data = yaml.safe_load(yaml_content)
            
            if not data or not isinstance(data, dict):
                return dependencies
            
            # Look for tables section
            tables = data.get('tables', {})
            if not isinstance(tables, dict):
                return dependencies
            
            # Look for base_table section
            base_tables = tables.get('base_table', [])
            if not isinstance(base_tables, list):
                base_tables = [base_tables] if base_tables else []
            
            # Extract database.schema.table from each base_table
            for base_table in base_tables:
                if not isinstance(base_table, dict):
                    continue
                
                database = base_table.get('database', '')
                schema = base_table.get('schema', '')
                table = base_table.get('table', '')
                
                if database and schema and table:
                    # Convert to uppercase and add to dependencies
                    full_name = f"{database.upper()}.{schema.upper()}.{table.upper()}"
                    dependencies.add(full_name)
            
        except yaml.YAMLError as e:
            raise ValueError(f"Failed to parse YAML for dependency extraction: {e}") from e
        except Exception as e:
            raise ValueError(f"Error extracting dependencies from semantic view YAML: {e}") from e
        
        return dependencies
