# -*- coding: utf-8 -*-
'''
传入金融逻辑描述
1, 拆分词条
2, 将词条作为 key, 在数据库查找, 获取合适使用的数据集
'''
import psycopg2
import jieba

def process_text(text):
    filter_list = ['\n', '\t', '\r', '\b', '\f', '\v', '：', '的', '或', '10', '天', '了', '可', '是', '该', '，', ' ', '、', '让', '和', '集',
                   '/', '日', '在', '（', '_', '-', ')', '(', '上', '距', '与', '比', '下', '及', '）', '...', '；', '%', '&', '+', ',', '.', 
                   ':', ';', '<', '=', '>', '?', '[', ']', '|', '—', '。'
    ]
    
    text_list = jieba.lcut(text)
    results = []
    for tl in text_list:
        should_include = True
        for fl in filter_list:
            if fl == tl:
                should_include = False
                break
        if should_include:
            results.append(tl)

    if results:
        return list(set(results))
    else:
        return None

def query_datasets_by_text(text):
    db_config = {
        'host': '192.168.31.201',
        'port': 5432,
        'database': 'alpha',
        'user': 'jack',
        'password': 'aaaAAA111'
    }

    keywords_list = process_text(text)
    
    if not keywords_list:
        print("未提取到有效关键词")
        return []
    
    print(f"提取到的关键词: {keywords_list}")
    
    return query_datasets_by_keywords(keywords_list, db_config)

def query_datasets_by_keywords(keywords_list, db_config):
    if not keywords_list:
        return []
    
    results = []
    
    try:
        conn = psycopg2.connect(**db_config)
        cur = conn.cursor()

        conditions = []
        params = []
        
        for keyword in keywords_list:
            conditions.append("name LIKE %s")
            params.append(f'%{keyword}%')
        
        sql = f"""
        SELECT * FROM data_sets
        WHERE {' OR '.join(conditions)}
        ORDER BY id ASC
        """
        
        cur.execute(sql, params)
        rows = cur.fetchall()
        
        for row in rows:
            results.append({
                "id": row[0],
                "name": row[1],
                "description": row[2],
            })
        
        cur.close()
        conn.close()
        
    except Exception as e:
        print(f"查询过程出错: {e}")
        raise
    
    return results


if __name__ == "__main__":
    test_text = """
    盈利
    """
    
    try:
        results = query_datasets_by_text(test_text)
        print(f"\n查询结果 ({len(results)} 条):")
        for result in results:
            print(result)
            
    except Exception as e:
        print(f"程序执行出错: {e}")