using FluidSim.Components;
using FluidSim.Core;
using FluidSim.Interfaces;
using SFML.Graphics;
using SFML.System;
using System;

namespace FluidSim.Tests
{
    public class SingleCylScenario : Scenario
    {
        private Crankshaft crankshaft;
        private Cylinder cylinder;

        private PipeSystem pipeSystem;
        private BoundarySystem boundaries;
        private Solver solver;

        private Volume0D intakePlenum;
        private Port plenumInlet, plenumOutlet;
        private Volume0D exhaustCollector;
        private Port colIn, colOut;

        private int throttleAreaIdx, plenumRunnerAreaIdx, intakeValveIdx, exhaustValveIdx;
        private float[] orificeAreas;
        private int intakeOpenIdx, exhaustOpenIdx;

        private SoundProcessor exhaustSound, intakeSound;
        private OutdoorExhaustReverb reverb;

        private double dt;
        private int stepCount;
        public float MaxThrottleArea = 1e-4f;   // 1 cm²

        // pipe area for open end calculations
        private float pipeArea;

        public override void Initialize(int sampleRate)
        {
            dt = 1.0 / sampleRate;

            // ---- Crankshaft ----
            crankshaft = new Crankshaft(600);
            crankshaft.Inertia = 0.2f;
            crankshaft.FrictionConstant = 2f;
            crankshaft.FrictionViscous = 0.04f;

            // ---- Cylinder ----
            float bore = 0.056f, stroke = 0.057f, conRod = 0.110f, compRatio = 9.2f;
            float ivo = 350f, ivc = 580f, evo = 120f, evc = 370f;
            cylinder = new Cylinder(bore, stroke, conRod, compRatio,
                                    ivo, ivc, evo, evc, crankshaft)
            {
                IntakeValveDiameter = 0.03f,
                IntakeValveLift = 0.005f,
                ExhaustValveDiameter = 0.028f,
                ExhaustValveLift = 0.005f
            };

            // ---- Pipe system ----
            int totalCells = 10 + 10 + 50;
            int[] pipeStart = { 0, 10, 20 };
            int[] pipeEnd = { 10, 20, 70 };
            float[] area = new float[totalCells];
            float[] dx = new float[totalCells];
            float pipeDiameter = 0.02f;          // 2 cm
            pipeArea = MathF.PI * 0.25f * pipeDiameter * pipeDiameter;
            float areaVal = pipeArea;
            float intakeLenBefore = 0.2f, intakeLenRunner = 0.2f, exhaustLen = 0.5f;
            for (int i = 0; i < totalCells; i++)
            {
                area[i] = areaVal;
                if (i < 10) dx[i] = intakeLenBefore / 10f;
                else if (i < 20) dx[i] = intakeLenRunner / 10f;
                else dx[i] = exhaustLen / 50f;
            }

            pipeSystem = new PipeSystem(totalCells, pipeStart, pipeEnd, area, dx,
                                        1.225f, 0f, 101325f);
            pipeSystem.DampingMultiplier = 0.5f;
            pipeSystem.EnergyRelaxationRate = 0f;
            pipeSystem.AmbientPressure = 101325f;

            // ---- Volumes ----
            intakePlenum = new Volume0D(5e-6f, 101325f, 300f);  // 5 mL
            plenumInlet = intakePlenum.CreatePort();
            plenumOutlet = intakePlenum.CreatePort();
            exhaustCollector = new Volume0D(10e-6f, 101325f, 800f);  // 10 mL (unused but present)
            colIn = exhaustCollector.CreatePort();
            colOut = exhaustCollector.CreatePort();

            // ---- Boundary system ----
            boundaries = new BoundarySystem(pipeSystem, maxOrifices: 4, maxOpenEnds: 2);

            throttleAreaIdx = 0;
            plenumRunnerAreaIdx = 1;
            intakeValveIdx = 2;
            exhaustValveIdx = 3;

            // Intake open end (pipe0 left)
            boundaries.AddOpenEnd(pipeIndex: 0, isLeftEnd: true, 101325f, pipeArea);
            intakeOpenIdx = 0;

            // Throttle orifice (plenum inlet to pipe0 right)
            boundaries.AddOrifice(plenumInlet, pipeIndex: 0, isLeftEnd: false, throttleAreaIdx, 0.2f);

            // Plenum to runner (plenum outlet to pipe1 left)
            boundaries.AddOrifice(plenumOutlet, pipeIndex: 1, isLeftEnd: true, plenumRunnerAreaIdx, 1f);

            // Intake valve (cylinder intake to pipe1 right)
            boundaries.AddOrifice(cylinder.IntakePort, pipeIndex: 1, isLeftEnd: false, intakeValveIdx, 1f);

            // Exhaust valve (cylinder exhaust to pipe2 left)
            boundaries.AddOrifice(cylinder.ExhaustPort, pipeIndex: 2, isLeftEnd: true, exhaustValveIdx, 1f);

            // Exhaust open end (pipe2 right)
            boundaries.AddOpenEnd(pipeIndex: 2, isLeftEnd: false, 101325f, pipeArea);
            exhaustOpenIdx = 1;

            orificeAreas = new float[4];
            orificeAreas[plenumRunnerAreaIdx] = areaVal; // fixed plenum->runner area

            // ---- Solver ----
            solver = new Solver { SubStepCount = 4, EnableProfiling = false };
            solver.SetTimeStep(dt);
            solver.SetPipeSystem(pipeSystem);
            solver.SetBoundarySystem(boundaries);
            solver.AddComponent(cylinder);
            solver.AddComponent(intakePlenum);
            solver.AddComponent(exhaustCollector);

            // ---- Sound ----
            exhaustSound = new SoundProcessor(sampleRate, 1f) { Gain = 1f };
            intakeSound = new SoundProcessor(sampleRate, 1f) { Gain = 1f };
            reverb = new OutdoorExhaustReverb(sampleRate);

            stepCount = 0;
            Console.WriteLine("TestScenario ready.");
        }

        public override float Process()
        {
            crankshaft.Step((float)dt);
            cylinder.PreStep((float)dt);

            // Update variable orifice areas
            float throttledArea = MaxThrottleArea * Math.Clamp(Throttle, 0.0001f, 1f);
            orificeAreas[throttleAreaIdx] = throttledArea;
            orificeAreas[intakeValveIdx] = cylinder.IntakeValveArea;
            orificeAreas[exhaustValveIdx] = cylinder.ExhaustValveArea;
            boundaries.SetOrificeAreas(orificeAreas);

            solver.Step();
            stepCount++;

            // Retrieve open‑end mass flows for sound synthesis
            float exhaustFlow = boundaries.GetOpenEndMassFlow(exhaustOpenIdx);
            float intakeFlow = boundaries.GetOpenEndMassFlow(intakeOpenIdx);

            float exhaustDry = exhaustSound.Process(exhaustFlow);
            float intakeDry = intakeSound.Process(intakeFlow);

            if (stepCount % 1000 == 0)
            {
                float rpm = crankshaft.AngularVelocity * 60f / (2f * MathF.PI);
                Console.WriteLine($"Step {stepCount}, RPM={rpm:F0}, CylP={cylinder.Pressure / 1e5f:F2} bar");
                Console.WriteLine($"intake flow: {intakeFlow:F12}, exhaust flow: {exhaustFlow:F16}");
            }

            return reverb.Process(intakeDry);
        }

        public override void Draw(RenderWindow target)
        {
            float winW = target.GetView().Size.X;
            float winH = target.GetView().Size.Y;

            float intakeY = winH / 2f - 40f;
            float exhaustY = winH / 2f + 80f;
            float openEndX = 40f;

            // Intake pipe before throttle (pipe 0)
            float pipe1StartX = openEndX;
            float pipe1EndX = pipe1StartX + 120f;
            DrawPipe(target, pipeSystem, 0, intakeY, pipe1StartX, pipe1EndX);

            // Throttle symbol
            float throttleX = pipe1EndX + 5f;
            var throttleRect = new RectangleShape(new Vector2f(8f, 30f))
            {
                FillColor = Color.Yellow,
                Position = new Vector2f(throttleX, intakeY - 15f)
            };
            target.Draw(throttleRect);

            // Plenum
            float plenW = 60f, plenH = 80f;
            float plenLeftX = throttleX + 10f;
            float plenCenterX = plenLeftX + plenW / 2f;
            float plenTopY = intakeY - plenH / 2f;
            DrawVolume(target, intakePlenum, plenCenterX, plenTopY, plenW, plenH);

            // Runner pipe (pipe 1)
            float runnerStartX = plenLeftX + plenW + 5f;
            float runnerEndX = runnerStartX + 100f;
            DrawPipe(target, pipeSystem, 1, intakeY, runnerStartX, runnerEndX);

            // Cylinder
            float cylCX = runnerEndX + 50f;
            float cylTopY = intakeY - 120f;
            float cylW = 80f, cylMaxH = 240f;
            DrawCylinder(target, cylinder, cylCX, cylTopY, cylW, cylMaxH);

            // Exhaust pipe (pipe 2)
            float exhStartX = cylCX + cylW / 2f + 20f;
            float exhEndX = winW - 60f;
            DrawPipe(target, pipeSystem, 2, exhaustY, exhStartX, exhEndX);
        }
    }
}