#!/bin/bash
# build_and_run.sh
# BINZIP Pipeline Docker 빌드 및 실행 스크립트

set -e

IMAGE_NAME="binzib-pipeline"
IMAGE_TAG="1.0"
CONTAINER_NAME="binzib-runner"

# 색상 출력
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN} BINZIB Pipeline Docker Setup${NC}"
echo -e "${GREEN}========================================${NC}"

# 1. 디렉토리 구조 확인
echo -e "\n${YELLOW}[1/4] 디렉토리 구조 확인${NC}"

if [ ! -f "requirements.txt" ]; then
    echo -e "${RED}ERROR: requirements.txt not found${NC}"
    exit 1
fi

if [ ! -d "wheels" ]; then
    echo -e "${RED}ERROR: wheels/ directory not found${NC}"
    echo "wheels 디렉토리에 whl 파일들을 넣어주세요"
    exit 1
fi

if [ ! -d "src" ]; then
    echo -e "${YELLOW}WARNING: src/ directory not found, creating empty${NC}"
    mkdir -p src
fi

echo "  requirements.txt: OK"
echo "  wheels/: $(ls wheels/*.whl 2>/dev/null | wc -l) files"
echo "  src/: OK"

# 2. Docker 이미지 빌드
echo -e "\n${YELLOW}[2/4] Docker 이미지 빌드${NC}"
docker build -t ${IMAGE_NAME}:${IMAGE_TAG} .

# 3. 이미지 확인
echo -e "\n${YELLOW}[3/4] 이미지 확인${NC}"
docker images ${IMAGE_NAME}:${IMAGE_TAG}

# 4. 테스트 실행
echo -e "\n${YELLOW}[4/4] 설치 테스트${NC}"
docker run --rm ${IMAGE_NAME}:${IMAGE_TAG} python -c "
import sys
print(f'Python: {sys.version}')
print(f'Prefix: {sys.prefix}')
print()

packages = [
    'pandas', 'numpy', 'oracledb', 'psycopg2', 'sqlalchemy',
    'geopandas', 'shapely', 'pyproj', 'joblib',
    'sklearn', 'scipy', 'matplotlib', 'seaborn',
    'xgboost', 'lightgbm', 'catboost', 'mgwr'
]

failed = []
for pkg in packages:
    try:
        mod = __import__(pkg)
        ver = getattr(mod, '__version__', 'N/A')
        print(f'  [OK] {pkg}: {ver}')
    except ImportError as e:
        print(f'  [FAIL] {pkg}: {e}')
        failed.append(pkg)

print()
if failed:
    print(f'Failed: {failed}')
    sys.exit(1)
else:
    print('All imports successful!')
"

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN} 빌드 완료!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "실행 방법:"
echo "  docker run -it --rm \\"
echo "    -v /path/to/data:/app/data \\"
echo "    -v /path/to/output:/app/output \\"
echo "    ${IMAGE_NAME}:${IMAGE_TAG} python src/pipeline.py"
