
import sys
import os
from pathlib import Path
import re

# Add backend directory to sys.path
backend_path = Path(__file__).parent
sys.path.insert(0, str(backend_path))

try:
    from database.connection import db
    print("Database connection imported successfully.")
except ImportError as e:
    print(f"Error importing database connection: {e}")
    sys.exit(1)

def is_ascii(s):
    return all(ord(c) < 128 for c in s)

def check_table(table_name, column_name):
    print(f"Checking table '{table_name}' column '{column_name}'...")
    try:
        query = f"SELECT DISTINCT {column_name} FROM {table_name}"
        rows = db.execute_query(query)
        
        found_invalid = False
        for row in rows:
            symbol = row.get(column_name)
            if symbol and not is_ascii(symbol):
                print(f"!!! FOUND INVALID SYMBOL in {table_name}: '{symbol}'")
                found_invalid = True
            if symbol and "币安" in symbol:
                print(f"!!! FOUND '币安' in {table_name}: '{symbol}'")
                found_invalid = True
                
        if not found_invalid:
            print(f"No invalid symbols found in {table_name}.")
            
    except Exception as e:
        print(f"Error querying {table_name}: {e}")

def check_config(table_name):
    print(f"Checking table '{table_name}' for '币安'...")
    try:
        query = f"SELECT config_key, config_value FROM {table_name}"
        rows = db.execute_query(query)
        
        for row in rows:
            key = row.get('config_key')
            val = row.get('config_value')
            
            if val and "币安" in str(val):
                # Ignore expected descriptions/comments if any (usually description is separate column)
                # But here we check config_value
                print(f"Found '币安' in {table_name} KEY='{key}': VALUE='{val}'")
                
            if key and "币安" in str(key):
                print(f"Found '币安' in {table_name} KEY='{key}'")

    except Exception as e:
        print(f"Error querying {table_name}: {e}")

if __name__ == "__main__":
    check_table("trades", "symbol")
    check_table("trade_recommendations", "symbol")
    check_config("trading_config")
    check_config("global_strategy_config")
