// Copyright 2026 sbqrre
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

///|
/// Scenario 1: Smart Home Environmental Monitor Demo.
pub fn run_environmental_monitor_demo() -> Unit {
  println("--- Scenario 1: Smart Home Environmental Monitor ---")
  let i2c_cfg = @i2c.I2cConfig::default_config()
  let i2c = @i2c.I2cMaster::new(i2c_cfg)
  let mpu_addr = @i2c.I2cAddress::Addr7Bit(0x68)

  let mem : Array[Byte] = Array::make(128, (0 : Byte))
  mem[0x75] = (0x68 : Byte)
  i2c.register_simulated_target(mpu_addr, mem)

  let mpu = @bsp.Mpu6050Driver::new(i2c, mpu_addr)
  let who = mpu.read_who_am_i().unwrap()
  println("MPU6050 Sensor Verified: WhoAmI = 0x" + who.to_int().to_string())

  let adc_cfg = @adc.AdcConfig::default_config()
  let adc = @adc.AdcController::new(adc_cfg)
  adc.set_simulated_channel_mv(1, 2400) // Ambient Light Sensor
  let light_mv = adc.read_mv(1).unwrap()
  println("Light Sensor Reading: " + light_mv.to_string() + "mV")
}

///|
/// Scenario 2: Industrial Servo Motor Closed-Loop Control Demo.
pub fn run_motor_control_demo() -> Unit {
  println("--- Scenario 2: Industrial Servo Motor Closed-Loop Control ---")
  let pwm_cfg = @pwm.PwmConfig::default_config()
  let pwm = @pwm.PwmTimer::new(pwm_cfg, 20000) // 50Hz Servo Frequency
  let _ = pwm.set_duty_cycle(@pwm.PwmChannel::Channel1, 0.075) // 1.5ms Neutral Pulse Width (7.5%)

  let pulse_ticks = pwm.get_pulse_ticks(@pwm.PwmChannel::Channel1)
  println(
    "Servo Motor Position set to 90 Degrees (Neutral). Pulse Ticks = " +
    pulse_ticks.to_string(),
  )
}

///|
/// Scenario 3: High-Speed SPI Data Logger Demo.
pub fn run_data_logger_demo() -> Unit {
  println("--- Scenario 3: High-Speed SPI Flash Data Logger ---")
  let spi_cfg = @spi.SpiConfig::default_config()
  let spi = @spi.SpiMaster::new(spi_cfg, None)
  let flash = @sim.W25q64Flash::new(spi)

  flash.write_enable()
  let _ = flash.erase_sector(0)
  flash.write_enable()
  let log_entry : Array[Byte] = [(0x5C : Byte), (0xA0 : Byte), (0xFF : Byte)]
  let _ = flash.program_page(0, log_entry)

  let read_back = flash.read_data(0, 3).unwrap()
  println("SPI Flash Log Byte 0: 0x" + read_back[0].to_int().to_string())
}