#!/usr/bin/env python3
"""
Download and extract Eigen headers for building gconcord.
"""
import os
import sys
import urllib.request
import tarfile
import shutil
from pathlib import Path

EIGEN_VERSION = "3.4.0"
EIGEN_URL = f"https://gitlab.com/libeigen/eigen/-/archive/{EIGEN_VERSION}/eigen-{EIGEN_VERSION}.tar.gz"

def download_eigen(dest_dir="."):
    """Download and extract Eigen headers."""
    dest_path = Path(dest_dir)
    eigen_dir = dest_path / f"eigen-{EIGEN_VERSION}"
    
    if eigen_dir.exists():
        print(f"Eigen {EIGEN_VERSION} already exists at {eigen_dir}")
        return eigen_dir
    
    # Download
    tar_path = dest_path / f"eigen-{EIGEN_VERSION}.tar.gz"
    print(f"Downloading Eigen {EIGEN_VERSION}...")
    urllib.request.urlretrieve(EIGEN_URL, tar_path)
    
    # Extract
    print(f"Extracting Eigen {EIGEN_VERSION}...")
    with tarfile.open(tar_path, "r:gz") as tar:
        tar.extractall(dest_path)
    
    # Clean up
    tar_path.unlink()
    
    print(f"Eigen {EIGEN_VERSION} downloaded to {eigen_dir}")
    return eigen_dir

if __name__ == "__main__":
    dest = sys.argv[1] if len(sys.argv) > 1 else "."
    download_eigen(dest)