"""
Create circular_plate_frequency_tuning_V2 study with ALL fixes applied.

Improvements:
- Proper study naming
- Reports go to 3_reports/ folder
- Reports discuss actual goal (115 Hz target)
- Fixed objective function
"""

from pathlib import Path
import sys
import argparse
sys.path.insert(0, str(Path(__file__).parent))

from optimization_engine.hybrid_study_creator import HybridStudyCreator


def main():
    parser = argparse.ArgumentParser(description='Create circular plate frequency tuning study')
    parser.add_argument('--study-name', default='circular_plate_frequency_tuning_V2',
                       help='Name of the study folder')
    args = parser.parse_args()

    study_name = args.study_name

    creator = HybridStudyCreator()

    # Create workflow JSON
    import json
    import tempfile
    workflow = {
        "study_name": study_name,
        "optimization_request": "Tune the first natural frequency mode to exactly 115 Hz (within 0.1 Hz tolerance)",
        "design_variables": [
            {"parameter": "inner_diameter", "bounds": [50, 150]},
            {"parameter": "plate_thickness", "bounds": [2, 10]}
        ],
        "objectives": [{
            "name": "frequency_error",
            "goal": "minimize",
            "extraction": {
                "action": "extract_first_natural_frequency",
                "params": {"mode_number": 1, "target_frequency": 115.0}
            }
        }],
        "constraints": [{
            "name": "frequency_tolerance",
            "type": "less_than",
            "threshold": 0.1
        }]
    }

    # Write to temp file
    temp_workflow = Path(tempfile.gettempdir()) / f"{study_name}_workflow.json"
    with open(temp_workflow, 'w') as f:
        json.dump(workflow, f, indent=2)

    # Create study
    study_dir = creator.create_from_workflow(
        workflow_json_path=temp_workflow,
        model_files={
            'prt': Path("examples/Models/Circular Plate/Circular_Plate.prt"),
            'sim': Path("examples/Models/Circular Plate/Circular_Plate_sim1.sim"),
            'fem': Path("examples/Models/Circular Plate/Circular_Plate_fem1.fem"),
            'fem_i': Path("examples/Models/Circular Plate/Circular_Plate_fem1_i.prt")
        },
        study_name=study_name
    )

    print()
    print("=" * 80)
    print(f"[OK] Study created: {study_name}")
    print("=" * 80)
    print()
    print(f"Location: {study_dir}")
    print()
    print("Structure:")
    print("  - 1_setup/: Model files and configuration")
    print("  - 2_results/: Optimization history and database")
    print("  - 3_reports/: Human-readable reports with graphs")
    print()
    print("To run optimization:")
    print(f"  python {study_dir}/run_optimization.py")
    print()


if __name__ == "__main__":
    main()
