import requests
import os
import time
import sys

# --- Configuration ---
# Load credentials from .env
def load_env_manual(path):
    """A simple parser for .env files to remove dependency on python-dotenv."""
    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" 
HEALTH_ENDPOINT = f"{CE_URL}/api/health"

def run_health_check():
    """
    Attempts to connect to the Company Explorer API health endpoint.
    """
    print("="*60)
    print("🩺 Running Company Explorer Health Check...")
    print(f"   Target: {HEALTH_ENDPOINT}")
    print("="*60)

    if not API_USER or not API_PASS:
        print("❌ FATAL: API_USER or API_PASSWORD not found in environment.")
        print("   Please check your .env file.")
        return False

    try:
        print("   Attempting to connect...")
        response = requests.get(HEALTH_ENDPOINT, auth=(API_USER, API_PASS), timeout=5)
        
        if response.status_code == 200:
            print("   ✅ SUCCESS: Connection successful!")
            print(f"   Server Response: {response.json()}")
            return True
        elif response.status_code == 401:
            print("   ❌ FAILURE: Connection successful, but Authentication failed (401).")
            print("   Please check API_USER and API_PASSWORD in your .env file.")
            return False
        else:
            print(f"   ❌ FAILURE: Connected, but received an error status code: {response.status_code}")
            print(f"   Response: {response.text}")
            return False

    except requests.exceptions.ConnectionError:
        print("   ❌ FATAL: Connection refused.")
        print("   Is the Company Explorer container running?")
        print(f"   Is port 8000 correctly mapped to {CE_URL}?")
        return False
    except requests.exceptions.Timeout:
        print("   ❌ FATAL: Connection timed out.")
        print("   The server is not responding. Check for high load or container issues.")
        return False
    except Exception as e:
        print(f"   ❌ An unexpected error occurred: {e}")
        return False

if __name__ == "__main__":
    if run_health_check():
        sys.exit(0) # Success
    else:
        sys.exit(1) # Failure
