import os
import re
import requests

API_URL = "http://commit-svc.aiplatform/publish"

def extract_default_image():
    """Extracts the image name from KERNEL_IMAGE if available and formats it."""
    kernel_image = os.getenv("KERNEL_IMAGE", "unname/unname_image@sha256:3024")
    image_name = kernel_image.split("/")[1].split("@")[0]  # Extract image name
    return format_name(image_name)

def format_name(name):
    """Ensure the name is lowercase and contains only valid characters."""
    return re.sub(r'[^a-z0-9_]', '_', name.lower())

def validate_image_name(image_name):
    """Validate image name format: lowercase, only alphanumeric and underscores."""
    return bool(re.fullmatch(r'[a-z0-9_]+', image_name))

def validate_tags(tags):
    """Validate tags: lowercase, alphanumeric with underscores, and no spaces."""
    tag_list = {tag.strip().lower() for tag in tags.split() if tag.strip()}  # Use set to remove duplicates

    if not tag_list:
        return None  # No valid tags
    
    for tag in tag_list:
        if not re.fullmatch(r'[a-z0-9_]+', tag):
            return None  # Found an invalid tag
    
    return list(tag_list)  # Convert back to list before returning

def get_username():
    """Retrieve the username from the environment variable KERNEL_AP_USER or use 'unname'."""
    username = os.getenv("KERNEL_AP_USER", "unname")
    return format_name(username)

def publish_env():
    """Handles the 'aap_utils publish env' command and sends a POST request."""
    username = get_username()
    default_image = extract_default_image()
    
    while True:
        image_name = input(f"Enter image name [{default_image}]: ").strip() or default_image
        image_name = format_name(image_name)
        if validate_image_name(image_name):
            break
        print("Invalid image name. Use only lowercase letters, numbers, or underscores (_).")

    while True:
        tags = input("Enter tags (separated by space): ").strip()
        formatted_tags = validate_tags(tags)
        if formatted_tags:
            break
        print("Invalid tags. Each tag must be lowercase, contain only letters, numbers, or underscores (_), and have no spaces.")

    data = {
        "username": username,
        "imagename": image_name,
        "tags": formatted_tags
    }

    print(f"Publishing environment: {username}/{image_name}:{" ".join(formatted_tags.split())}")

    try:
        response = requests.post(API_URL, json=data)
        if response.status_code == 200:
            response_json = response.json()
            if response_json.get("result") == "success":
                print("✅ Successfully published the environment!")
            else:
                error_message = response_json.get("error", "Unknown error occurred.")
                print(f"❌ Failed to publish: {error_message}")
        else:
            print(f"❌ Failed to publish. Server responded with: {response.status_code}, {response.text}")
    except requests.RequestException as e:
        print(f"❌ Error connecting to the server: {e}")

def main():
    import sys
    if len(sys.argv) > 2 and sys.argv[1] == "publish" and sys.argv[2] == "env":
        publish_env()
    else:
        print("Usage: aap_utils publish env")
