"""
Flask App for Synthetic Data Generation
"""
from flask import Flask, render_template, request, jsonify
import sys
from pathlib import Path

# Add src to path
sys.path.insert(0, str(Path(__file__).parent))

from generator import SyntheticDataGenerator
from validator import DataValidator
import traceback

app = Flask(__name__)

# Initialize generator once
generator = None


def get_generator():
    """Lazy initialization of generator"""
    global generator
    if generator is None:
        generator = SyntheticDataGenerator()
    return generator


@app.route('/')
def index():
    """Serve the main page"""
    return render_template('index.html')


@app.route('/generate', methods=['POST'])
def generate():
    """
    Generate synthetic data endpoint

    Expects JSON:
    {
        "simulation_length": int,
        "volatility": float
    }
    """
    try:
        data = request.get_json()
        simulation_length = int(data.get('simulation_length', 1000))
        volatility = float(data.get('volatility', 1.0))

        # Validate inputs
        if simulation_length < 100:
            return jsonify({'error': 'Simulation length must be at least 100'}), 400
        if simulation_length > 100000:
            return jsonify({'error': 'Simulation length cannot exceed 100,000'}), 400
        if volatility < 0.1 or volatility > 10:
            return jsonify({'error': 'Volatility must be between 0.1 and 10'}), 400

        # Generate data
        print(f"Generating {simulation_length} points with {volatility}x volatility...")
        gen = get_generator()
        df, filepath = gen.generate_synthetic_data(simulation_length, volatility)

        # Validate data
        print("Validating data...")
        validator = DataValidator(df)
        report = validator.validate_and_report()

        # Add filepath to report
        report['filepath'] = filepath
        report['filename'] = Path(filepath).name

        # Data preview (first and last 10 rows)
        preview = {
            'head': df.head(10).reset_index().to_dict('records'),
            'tail': df.tail(10).reset_index().to_dict('records')
        }
        report['preview'] = preview

        print("Generation complete!")
        return jsonify(report)

    except Exception as e:
        print(f"Error: {str(e)}")
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500


@app.route('/health')
def health():
    """Health check endpoint"""
    return jsonify({'status': 'healthy', 'service': 'Synthetic Data Generator'})


if __name__ == '__main__':
    print("Starting Synthetic Data Generator Flask App...")
    print("Visit http://localhost:5000")
    app.run(debug=True, host='0.0.0.0', port=5000)
