import requests
import os

# --- Configuration ---
def load_env_manual(path):
    if not os.path.exists(path):
        print(f"⚠️  Warning: .env file not found at {path}")
        return
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#') and '=' in line:
                key, val = line.split('=', 1)
                os.environ.setdefault(key.strip(), val.strip())

load_env_manual('/app/.env')

API_USER = os.getenv("API_USER")
API_PASS = os.getenv("API_PASSWORD")
CE_URL = "http://127.0.0.1:8000"

endpoints_to_check = {
    "Industries": "/api/industries",
    "Robotics Categories": "/api/robotics/categories",
    "Job Roles": "/api/job_roles"
}

def check_settings_endpoints():
    print("="*60)
    print("🩺 Running Settings Endpoints Health Check...")
    print("="*60)

    all_ok = True
    for name, endpoint in endpoints_to_check.items():
        url = f"{CE_URL}{endpoint}"
        print(f"--- Checking {name} ({url}) ---")
        try:
            response = requests.get(url, auth=(API_USER, API_PASS), timeout=5)
            if response.status_code == 200:
                print(f"   ✅ SUCCESS: Received {len(response.json())} items.")
            else:
                print(f"   ❌ FAILURE: Status {response.status_code}, Response: {response.text}")
                all_ok = False
        except requests.exceptions.RequestException as e:
            print(f"   ❌ FATAL: Connection error: {e}")
            all_ok = False

    return all_ok

if __name__ == "__main__":
    if check_settings_endpoints():
        print("\n✅ All settings endpoints are healthy.")
    else:
        print("\n🔥 One or more settings endpoints failed.")
        exit(1)
