#!/usr/bin/env python3

import argparse
import json
import sys
import requests
from typing import Optional

def get_docker_hub_labels(image_name: str, tag: str, username: str, password: str) -> Optional[dict]:
    """
    Estrae le etichette (labels) da un'immagine Docker su Docker Hub.

    Args:
        image_name: Il nome del repository dell'immagine (es. 'costergroup/webgarage').
        tag: Il tag dell'immagine (es. 'ehc-latest').
        username: Nome utente di Docker Hub.
        password: Password o token di accesso di Docker Hub.

    Returns:
        Un dizionario contenente le etichette dell'immagine, o None se non trovate.
    """
    # 1. Ottieni il token di autenticazione
    print("1. Autenticazione a Docker Hub...", file=sys.stderr)
    auth_url = "https://auth.docker.io/token"
    auth_params = {
        "service": "registry.docker.io",
        "scope": f"repository:{image_name}:pull"
    }
    try:
        auth_response = requests.get(auth_url, params=auth_params, auth=(username, password))
        auth_response.raise_for_status()
        auth_token = auth_response.json().get("token")
        if not auth_token:
            print("Errore: Token di autenticazione non ricevuto. Controlla le credenziali.", file=sys.stderr)
            return None
    except requests.exceptions.RequestException as e:
        print(f"Errore durante l'autenticazione: {e}", file=sys.stderr)
        return None

    auth_header = {"Authorization": f"Bearer {auth_token}"}

    # 2. Ottieni il manifest dell'immagine
    print("2. Recupero del manifest dell'immagine...", file=sys.stderr)
    manifest_url = f"https://registry-1.docker.io/v2/{image_name}/manifests/{tag}"
    manifest_headers = {
        "Accept": "application/vnd.docker.distribution.manifest.v2+json",
        **auth_header
    }
    try:
        manifest_response = requests.get(manifest_url, headers=manifest_headers)
        manifest_response.raise_for_status()
        manifest_data = manifest_response.json()
    except requests.exceptions.RequestException as e:
        print(f"Errore nel recupero del manifest: {e}", file=sys.stderr)
        print("L'immagine o il tag potrebbero non esistere.", file=sys.stderr)
        return None
    except json.JSONDecodeError:
        print("Errore: Risposta del manifest non è un JSON valido.", file=sys.stderr)
        print(f"Risposta ricevuta: {manifest_response.text}", file=sys.stderr)
        return None

    config_info = manifest_data.get("config")
    if not config_info or "digest" not in config_info:
        print("Errore: Impossibile trovare il digest della configurazione nel manifest.", file=sys.stderr)
        return None

    config_digest = config_info["digest"]
    config_media_type = config_info.get("mediaType", "application/octet-stream")

    # 3. Ottieni il blob di configurazione
    print("3. Recupero del blob di configurazione...", file=sys.stderr)
    config_url = f"https://registry-1.docker.io/v2/{image_name}/blobs/{config_digest}"
    config_headers = {
        "Accept": config_media_type,
        **auth_header
    }
    try:
        config_response = requests.get(config_url, headers=config_headers)
        config_response.raise_for_status()
        config_data = config_response.json()
    except requests.exceptions.RequestException as e:
        print(f"Errore nel recupero del blob di configurazione: {e}", file=sys.stderr)
        return None
    except json.JSONDecodeError:
        print("Errore: Risposta della configurazione non è un JSON valido.", file=sys.stderr)
        return None

    # 4. Estrai le etichette
    labels = config_data.get("config", {}).get("Labels")
    return labels

def main():
    parser = argparse.ArgumentParser(description="Estrae le etichette da un'immagine Docker Hub.")
    parser.add_argument("image_name", help="Nome del repository dell'immagine (es. 'costergroup/webgarage')")
    parser.add_argument("tag", help="Tag dell'immagine (es. 'ehc-latest')")
    parser.add_argument("username", help="Nome utente di Docker Hub")
    parser.add_argument("password", help="Password o token di accesso di Docker Hub")
    args = parser.parse_args()

    labels = get_docker_hub_labels(args.image_name, args.tag, args.username, args.password)

    if labels:
        result = {
            "version": labels.get("version", ""),
            "finVersion": labels.get("finVersion", ""),
            "error": ""
        }
    else:
        result = {
            "version": "",
            "finVersion": "",
            "error": "Labels not found or an error occurred"
        }

    print(json.dumps(result))

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(json.dumps({"version": "", "finVersion": "", "error": str(e)}))
