"""
Reference data loader with S3 auto-download support.

Provides S3-only access to reference data with automatic download and caching.
No local file fallbacks - forces users to use S3 or explicit commands.
"""

import os
from pathlib import Path
from typing import Optional

import polars as pl
from rich.console import Console

from ...services.s3_data_service import S3DataService
from ...services.environment_service import env_service

console = Console()


def load_reference_data() -> Optional[pl.DataFrame]:
    """
    Load reference data from S3 with auto-download.
    
    S3-only loading strategy:
    1. Load environment variables from ~/.czbillgen/.env
    2. Check S3 configuration
    3. Auto-download from S3 if needed
    4. Return cached data or None if S3 not configured
    
    Returns:
        DataFrame with reference data or None if S3 not configured
    """
    # Environment service automatically loads ~/.czbillgen/.env
    # Check if S3 is configured (only need bucket - AWS credentials handled by boto3 default chain)
    s3_configured = env_service.is_configured("CZBILLGEN_S3_BUCKET")
    
    if not s3_configured:
        return None
    
    try:
        console.print("🔄 Loading reference data from S3 (auto-download if needed)...", style="dim")
        
        s3_service = S3DataService()
        cached_path = s3_service.ensure_reference_data()
        
        df = pl.read_parquet(cached_path)
        console.print(f"✅ Loaded reference data from S3: {df.height:,} rows", style="dim green")
        return df
        
    except Exception as e:
        console.print(f"❌ S3 reference data loading failed: {e}", style="red")
        return None


def ensure_reference_data_available() -> bool:
    """
    Ensure reference data is available from S3, showing helpful messages if not.
    
    Returns:
        True if reference data is available, False otherwise
    """
    df = load_reference_data()
    
    if df is None:
        console.print()
        console.print("❌ S3 reference data not available", style="bold red")
        console.print()
        console.print("📋 Setup required:", style="bold yellow")
        console.print("  1. Configure S3 in ~/.czbillgen/.env")
        console.print("  2. Download reference data: czbillgen data download")
        console.print("  3. Or add exports to create data: czbillgen data add export <file>")
        console.print()
        return False
    
    return True