#!/usr/bin/env python3
"""
Fix university types in the database.
This script updates uni_type based on university names.
"""

import requests
import json
import sys

API_BASE = "https://macmini:8089/api/v1"

# Classification rules based on name patterns
UNI_TYPE_RULES = {
    "UNI": [
        "Universität", "University", "TU ", "TUM", "LMU", "RWTH",
        "Humboldt", "FU Berlin", "HU Berlin", "TH ", "KIT"
    ],
    "FH": [
        "Hochschule", "Fachhochschule", "FH ", "HAW ", "HS ",
        "University of Applied", "Beuth", "HTW"
    ],
    "RESEARCH": [
        "Fraunhofer", "Max-Planck", "Helmholtz", "DLR", "DESY",
        "DKFZ", "FZ Jülich", "AWI", "GFZ", "GSI", "Leibniz"
    ],
    "PRIVATE": [
        "EBS", "ESMT", "Bucerius", "WHU", "HHL", "FOM", "IUBH",
        "SRH", "International School", "Business School"
    ],
    "KUNST": [
        "Kunsthochschule", "Musikhochschule", "Filmhochschule",
        "Kunstakademie", "HfK", "HfM", "HfG", "UdK", "Bauhaus"
    ],
    "PH": [
        "Pädagogische Hochschule", "PH "
    ]
}

def classify_university(name):
    """Classify university by name patterns."""
    name_lower = name.lower()

    # Check each category
    for uni_type, patterns in UNI_TYPE_RULES.items():
        for pattern in patterns:
            if pattern.lower() in name_lower:
                return uni_type

    # Default to UNI if "universität" in name, else FH
    if "universität" in name_lower or "university" in name_lower:
        return "UNI"

    return "FH"  # Default

def get_all_universities():
    """Get list of all universities from the API."""
    try:
        response = requests.get(f"{API_BASE}/universities", verify=False, timeout=30)
        if response.status_code == 200:
            data = response.json()
            return data.get('universities', [])
    except Exception as e:
        print(f"Error fetching universities: {e}")
    return []

def update_university_type(uni_id, uni_type, uni_state=None):
    """Update university type via direct database or API."""
    # The API doesn't have an update endpoint, so we'll print SQL statements
    return uni_type

def main():
    print("=== University Type Fixer ===\n")

    # Disable SSL warnings
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    universities = get_all_universities()
    if not universities:
        print("ERROR: No universities found!")
        return

    print(f"Found {len(universities)} universities\n")

    # Classify and generate SQL
    sql_statements = []
    type_counts = {}

    for uni in universities:
        uni_id = uni['id']
        uni_name = uni['name']
        current_type = uni.get('uni_type', 'unknown')

        # Classify
        new_type = classify_university(uni_name)

        # Count
        type_counts[new_type] = type_counts.get(new_type, 0) + 1

        # Generate SQL
        sql = f"UPDATE universities SET uni_type = '{new_type}' WHERE id = '{uni_id}';"
        sql_statements.append(sql)

        if current_type != new_type:
            print(f"  {uni_name[:50]:<50} -> {new_type}")

    print(f"\n=== Summary ===")
    for t, c in sorted(type_counts.items()):
        print(f"  {t}: {c}")

    # Write SQL file
    sql_file = "/tmp/fix_uni_types.sql"
    with open(sql_file, 'w') as f:
        f.write("-- Fix university types\n")
        f.write("BEGIN;\n\n")
        for sql in sql_statements:
            f.write(sql + "\n")
        f.write("\nCOMMIT;\n")

    print(f"\nSQL written to: {sql_file}")
    print(f"Run: cat {sql_file} | docker exec -i breakpilot-pwa-postgres psql -U <user> -d edu_search")

if __name__ == "__main__":
    main()
