#!/bin/bash

# PGE Energy Report Processing Pipeline
# Complete workflow from CSV conversion to visualization dashboard

set -e  # Exit on error

# Configuration
INPUT_FILE="$1"
OUTPUT_DIR="${2:-output}"
BUY_PRICE="${3:-1.4}"
SELL_PRICE="${4:-0.2}"
BASE_FILENAME=$(basename "$INPUT_FILE" .csv)
PYTHON_CMD="/home/postio-admin/pge-raport/.venv/bin/python"

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}🔌 PGE Energy Report Processing Pipeline${NC}"
echo "=================================================="

# Check if input file provided
if [ -z "$INPUT_FILE" ]; then
    echo -e "${RED}Error: Please provide input CSV file${NC}"
    echo "Usage: $0 <input_file.csv> [output_directory] [buy_price] [sell_price]"
    echo "Default prices: buy=1.4 PLN/kWh, sell=0.2 PLN/kWh"
    exit 1
fi

# Check if input file exists
if [ ! -f "$INPUT_FILE" ]; then
    echo -e "${RED}Error: Input file not found: $INPUT_FILE${NC}"
    exit 1
fi

echo -e "${YELLOW}📋 Configuration:${NC}"
echo "  Input file: $INPUT_FILE"
echo "  Output directory: $OUTPUT_DIR"
echo "  Base filename: $BASE_FILENAME"
echo "  Energy prices: Buy=$BUY_PRICE PLN/kWh, Sell=$SELL_PRICE PLN/kWh"
echo ""

# Step 1: Convert CSV data
echo -e "${BLUE}📊 Step 1: Converting CSV data...${NC}"
$PYTHON_CMD raport_convert.py "$INPUT_FILE" --output-dir "$OUTPUT_DIR"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Data conversion completed${NC}"
else
    echo -e "${RED}✗ Data conversion failed${NC}"
    exit 1
fi
echo ""

# Step 2: Generate charts
echo -e "${BLUE}📈 Step 2: Generating visualizations...${NC}"
$PYTHON_CMD visualize_data.py "$BASE_FILENAME" --data-dir "$OUTPUT_DIR" --output-dir "$OUTPUT_DIR/charts" --buy-price "$BUY_PRICE" --sell-price "$SELL_PRICE"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Chart generation completed${NC}"
else
    echo -e "${RED}✗ Chart generation failed${NC}"
    exit 1
fi
echo ""

# Step 3: Create HTML dashboard
echo -e "${BLUE}🌐 Step 3: Creating HTML dashboard...${NC}"
$PYTHON_CMD create_dashboard.py "$BASE_FILENAME" --charts-dir "$OUTPUT_DIR/charts" --output "$OUTPUT_DIR/dashboard.html"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Dashboard creation completed${NC}"
else
    echo -e "${RED}✗ Dashboard creation failed${NC}"
    exit 1
fi
echo ""

# Summary
echo -e "${GREEN}🎉 Pipeline completed successfully!${NC}"
echo "=================================================="
echo -e "${YELLOW}📁 Generated files:${NC}"
echo "  Data files: $OUTPUT_DIR/*-hourly.csv, *-daily.csv, *-weekly.csv, *-monthly.csv"
echo "  Charts: $OUTPUT_DIR/charts/*.png"
echo "  Dashboard: $OUTPUT_DIR/dashboard.html"
echo ""
echo -e "${BLUE}🌐 Open dashboard in browser:${NC}"
echo "  file://$(pwd)/$OUTPUT_DIR/dashboard.html"