
import requests
import sys

def get_pypi_data(package_name, version):
    print(f"Fetching {package_name} {version}...", file=sys.stderr, flush=True)
    # PyPI JSON API: https://pypi.org/pypi/<package_name>/<version>/json
    url = f"https://pypi.org/pypi/{package_name}/{version}/json"
    try:
        resp = requests.get(url, timeout=10)
    except Exception as e:
        print(f"Check failed for {package_name}: {e}", file=sys.stderr)
        return None
        
    if resp.status_code != 200:
        print(f"Error fetching {package_name} {version}: {resp.status_code}", file=sys.stderr)
        return None
    return resp.json()

def generate_resource_block(package_name, version):
    data = get_pypi_data(package_name, version)
    if not data:
        return ""
    
    # helper: prefer source tarball, else wheel suitable for mac/multi-platform
    keys = ["sdist", "bdist_wheel"]
    
    urls = data['urls']
    if not urls:
        print(f"No URLs found for {package_name}", file=sys.stderr)
        return ""
        
    # try to find sdist first
    selected = next((u for u in urls if u['packagetype'] == 'sdist'), None)
    
    # if no sdist, find a universal wheel or macos wheel
    if not selected:
        for u in urls:
            if u['packagetype'] == 'bdist_wheel':
                fname = u['filename']
                if "macosx" in fname or "any" in fname:
                    selected = u
                    break
                    
    selected = selected or urls[0]
        
    url = selected['url']
    sha256 = selected['digests']['sha256']
    
    return f"""  resource "{package_name}" do
    url "{url}"
    sha256 "{sha256}"
  end
"""

def main():
    try:
        with open("requirements.txt") as f:
            lines = f.readlines()
    except FileNotFoundError:
        print("requirements.txt not found", file=sys.stderr)
        return
    
    ignore_list = ["medgemma", "homebrew-pypi-poet", "setuptools"] 
    
    for line in lines:
        line = line.strip()
        if not line or line.startswith("#"): continue
        if " @ " in line: continue # skip local/git deps
        
        parts = line.split("==")
        if len(parts) != 2: continue
        
        pkg, ver = parts[0], parts[1]
        
        if pkg in ignore_list: continue
        
        print(generate_resource_block(pkg, ver))

if __name__ == "__main__":
    main()
