#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Command-line search script - called by PHP
Usage: python3 python_search.py "search_term"
Output: JSON array of items
"""

import json
import sys
import pymysql
import os
from configparser import ConfigParser

CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'db_config.ini')

def load_db_config():
    """Load database config from ini file"""
    parser = ConfigParser()
    parser.read(CONFIG_PATH)
    config = parser['database']
    return {
        'host': config.get('host', 'localhost'),
        'user': config.get('user'),
        'password': config.get('password'),
        'database': config.get('database'),
        'charset': 'utf8mb4',
        'autocommit': True
    }

def search_items(query):
    """Search items in database"""
    print(f"# DEBUG: search_items called with '{query}'", file=sys.stderr)
    
    if len(query.strip()) < 2:
        print("# DEBUG: Query too short", file=sys.stderr)
        return []
    
    try:
        print("# DEBUG: Loading config...", file=sys.stderr)
        config = load_db_config()
        print(f"# DEBUG: Connecting to DB: {config['host']}", file=sys.stderr)
        conn = pymysql.connect(**config)
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        print("# DEBUG: Connected successfully", file=sys.stderr)
        
        sql = """
            SELECT id, number, name, active
            FROM items 
            WHERE (number LIKE %s OR name LIKE %s)
            AND active = 1
            ORDER BY 
                CASE 
                    WHEN number LIKE %s THEN 1 
                    WHEN name LIKE %s THEN 2 
                    ELSE 3 
                END,
                name ASC, number ASC
            LIMIT 20
        """
        
        search_param = f"%{query}%"
        search_param_start = f"{query}%"
        print(f"# DEBUG: SQL params: {search_param}", file=sys.stderr)
        
        cursor.execute(sql, (search_param, search_param, search_param_start, search_param_start))
        results = cursor.fetchall()
        print(f"# DEBUG: Raw SQL results: {len(results)} rows", file=sys.stderr)
        
        # Test: try without active filter
        test_sql = "SELECT COUNT(*) as total FROM items WHERE (number LIKE %s OR name LIKE %s)"
        cursor.execute(test_sql, (search_param, search_param))
        total = cursor.fetchone()
        print(f"# DEBUG: Total matches (any active): {total}", file=sys.stderr)
        
        items = []
        for row in results:
            status = ' || aktiv' if row['active'] else ' || inaktiv'
            items.append({
                'id': row['id'],
                'value': row['number'],
                'label': f"{row['name']} ({row['number']}{status})",
                'number': row['number'],
                'name': row['name'],
                'active': row['active']
            })
        
        cursor.close()
        conn.close()
        return items
        
    except Exception as e:
        # Return empty array on error - let PHP fallback handle it
        return []

if __name__ == '__main__':
    print("# DEBUG: Script started", file=sys.stderr)
    print(f"# DEBUG: Args: {sys.argv}", file=sys.stderr)
    
    if len(sys.argv) != 2:
        print("# DEBUG: Wrong number of args", file=sys.stderr)
        print("[]")
        sys.exit(1)
    
    search_query = sys.argv[1]
    print(f"# DEBUG: Searching for '{search_query}'", file=sys.stderr)
    
    try:
        results = search_items(search_query)
        print(f"# DEBUG: Got results: {results}", file=sys.stderr)
        print(json.dumps(results))
    except Exception as e:
        print(f"# DEBUG: Exception: {e}", file=sys.stderr)
        import traceback
        traceback.print_exc(file=sys.stderr)
        print("[]")