"""
Setup Beam Optimization Study

This script configures the optimization study based on benchmarking results:
- Design variables: beam_half_core_thickness, beam_face_thickness, holes_diameter, hole_count
- Objectives: Minimize stress AND minimize weight (p173 mass)
- Constraint: max_displacement < 10mm
"""

import sys
import json
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from optimization_engine.study.creator import StudyCreator


def main():
    print()
    print("="*80)
    print("SIMPLE BEAM OPTIMIZATION - SETUP")
    print("="*80)
    print()

    # Load configuration
    config_file = Path('studies/simple_beam_optimization/beam_optimization_config.json')

    if not config_file.exists():
        print(f"[ERROR] Configuration file not found: {config_file}")
        return False

    with open(config_file, 'r') as f:
        config = json.load(f)

    print("Configuration loaded:")
    print(f"  Study: {config['study_name']}")
    print(f"  Substudy: {config['substudy_name']}")
    print()

    print("Design Variables:")
    for name, info in config['design_variables'].items():
        print(f"  - {name}: [{info['min']}, {info['max']}] {info['units']} (baseline: {info['baseline']})")
    print()

    print("Objectives:")
    for obj in config['objectives']:
        print(f"  - {obj['name']}: {obj['goal']} (weight: {obj['weight']})")
    print()

    print("Constraints:")
    for const in config['constraints']:
        print(f"  - {const['name']}: {const['extractor']} {const['type']} {const['value']} {const['units']}")
    print()

    # Create substudy
    creator = StudyCreator()
    study_dir = Path('studies') / config['study_name']

    print(f"Creating substudy '{config['substudy_name']}'...")

    try:
        substudy_dir = creator.create_substudy(
            study_dir=study_dir,
            substudy_name=config['substudy_name'],
            config=config
        )

        print(f"[SUCCESS] Substudy created: {substudy_dir}")
        print()

        # Save configuration to substudy
        substudy_config_file = substudy_dir / "optimization_config.json"
        with open(substudy_config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2)

        print(f"[OK] Configuration saved to: {substudy_config_file}")
        print()

        print("="*80)
        print("NEXT STEPS")
        print("="*80)
        print()
        print("1. Review configuration:")
        print(f"   {substudy_config_file}")
        print()
        print("2. Run initial trials to validate pipeline:")
        print(f"   python tests/run_initial_trials.py")
        print()
        print("3. If validation passes, run full optimization:")
        print(f"   python run_optimization.py studies/{config['study_name']} --substudy {config['substudy_name']}")
        print()

        return True

    except Exception as e:
        print(f"[ERROR] Failed to create substudy: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
