package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "regexp"
    "sort"
)

type ReleaseInfo struct {
    RequiresPython string `json:"requires_python"`
}

type PackageInfo struct {
    Info struct {
        Name    string `json:"name"`
        Version string `json:"version"`
        Summary string `json:"summary"`
    } `json:"info"`
    Releases map[string][]ReleaseInfo `json:"releases"`
}

func main() {

    if len(os.Args) < 2 {
        fmt.Println("Uso: pipinfo <paquete> [--all]")
        return
    }

    pkg := os.Args[1]
    showAll := len(os.Args) > 2 && os.Args[2] == "--all"

    url := fmt.Sprintf("https://pypi.org/pypi/%s/json", pkg)

    resp, err := http.Get(url)
    if err != nil {
        fmt.Printf("❌ Error de conexión: %v\n", err)
        return
    }
    defer resp.Body.Close()

    if resp.StatusCode != 200 {
        fmt.Printf("❌ No se encontró el paquete '%s'\n", pkg)
        return
    }

    var data PackageInfo
    if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
        fmt.Printf("❌ Error procesando JSON: %v\n", err)
        return
    }

    fmt.Printf("📦 Paquete: %s\n", data.Info.Name)
    fmt.Printf("🔢 Última versión: %s\n", data.Info.Version)
    fmt.Printf("📝 Descripción: %s\n\n", data.Info.Summary)

    // Obtener lista de versiones
    versions := make([]string, 0, len(data.Releases))
    for v := range data.Releases {
        versions = append(versions, v)
    }

    sort.Slice(versions, func(i, j int) bool {
        return versions[i] > versions[j]
    })

    stableRegex := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)

    count := 0

    if showAll {
        fmt.Println("📚 Todas las versiones:")
        for _, v := range versions {
            req := "N/A"
            if len(data.Releases[v]) > 0 && data.Releases[v][0].RequiresPython != "" {
                req = data.Releases[v][0].RequiresPython
            }
            fmt.Printf("  %-12s (Python %s)\n", v, req)
        }
    } else {
        fmt.Println("📚 Últimas 10 versiones estables:\n")
        for _, v := range versions {
            if stableRegex.MatchString(v) {
                req := "N/A"
                if len(data.Releases[v]) > 0 && data.Releases[v][0].RequiresPython != "" {
                    req = data.Releases[v][0].RequiresPython
                }
                fmt.Printf("  %-12s (Python %s)\n", v, req)
                count++
                if count == 10 {
                    break
                }
            }
        }
    }
}
