#!/usr/bin/env python3
"""
Configuration Loader - Phase 5
Loads filtering and keyword configuration from database lookup tables
"""

import mysql.connector
import json
import sys

def load_db_config(config_path="../db-config.json"):
    """Load database configuration from JSON file"""
    try:
        with open(config_path) as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"[ERROR] Database config file not found: {config_path}")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"[ERROR] Invalid JSON in config file: {e}")
        sys.exit(1)

def get_db_connection(config_path="../db-config.json"):
    """Create and return database connection"""
    db_cfg = load_db_config(config_path)
    try:
        conn = mysql.connector.connect(**db_cfg)
        return conn
    except mysql.connector.Error as e:
        print(f"[ERROR] Database connection failed: {e}")
        sys.exit(1)

def load_scraper_config(cursor):
    config = {"exclude_prefixes": [], "keywords": [], "exclude_keywords": []}
    
    cursor.execute("""
        SELECT f.lk_nm, v.lk_val
        FROM feature_lk f
        JOIN feature_lk_val v ON f.idfeature_lk = v.idfeature_lk
        WHERE f.lk_nm IN ('Main Page Exclude', 'ML Include', 'ML Exclude')
    """)
    
    for lk_nm, lk_val in cursor.fetchall():
        if lk_nm == "Main Page Exclude":
            config["exclude_prefixes"].append(lk_val.upper())
        elif lk_nm == "ML Include":
            config["keywords"].append(lk_val)
        elif lk_nm == "ML Exclude":
            config["exclude_keywords"].append(lk_val)
    
    return config
