module FoilLab

using WaterLily, StaticArrays, LinearAlgebra, Statistics, Plots

export NACA4, CustomFoil, StaticMotion, FlappingMotion,
       run_sim, evaluate_airfoil

# ==============================================================================
# FoilLab.jl —— 《流体与仿生》三讲共享核心模块
#   第 1 讲（升力原理）：NACA4 / CustomFoil + StaticMotion
#   第 2 讲（扑翼推力）：复用翼型 + FlappingMotion（自动开启 remeasure=true）
#   第 3 讲（优化算法）：复用 evaluate_airfoil(x) 标量目标接口接入优化器
# ==============================================================================

# ---------- 1. 翼型几何定义 ----------
abstract type AbstractFoil end

"""
    NACA4(m, p, t)

NACA 4 位数风格参数化翼型：
- `m`：最大弯度（如 0.00 为对称翼，0.06 为 6% 弯度）
- `p`：最大弯度位置（0.15 ~ 0.80）
- `t`：最大相对厚度（相对弦长，建议 >= 2/L）
"""
struct NACA4 <: AbstractFoil
    m::Float64
    p::Float64
    t::Float64
end

"""
    CustomFoil(yc, yt)

自定义翼型：传入弯度线函数 `yc(s)` 与相对总厚度函数 `yt(s)`（`s ∈ [0, 1]`）。
"""
struct CustomFoil{F1,F2} <: AbstractFoil
    yc::F1
    yt::F2
end

# ---------- 2. 运动模式定义 ----------
abstract type AbstractMotion end

"""
    StaticMotion(α_deg=15.0; pivot=0.25)

静止固定攻角模式（第 1 讲默认）。
"""
struct StaticMotion <: AbstractMotion
    α_deg::Float64
    pivot::Float64
end
StaticMotion(α_deg=15.0; pivot=0.25) = StaticMotion(Float64(α_deg), Float64(pivot))

"""
    FlappingMotion(; St=0.30, h0=0.5, θ0_deg=20.0, ϕ_deg=90.0, α0_deg=0.0, pivot=0.25)

沉浮 + 俯仰扑翼模式（第 2 讲默认）：
- `y_h(t) = h0*L * sin(ωt)`
- `θ(t)   = α0 + θ0 * sin(ωt + ϕ)`
- `St = f * (2*h0*L) / U`（若 `h0 == 0` 纯俯仰，则按 `f*L/U = St` 计算频率）
- 经典高效推力区：`St ≈ 0.25 ~ 0.40`，`ϕ ≈ 90°`（俯仰超前沉浮 90°）
"""
struct FlappingMotion <: AbstractMotion
    St::Float64
    h0::Float64
    θ0_deg::Float64
    ϕ_deg::Float64
    α0_deg::Float64
    pivot::Float64
end
FlappingMotion(; St=0.30, h0=0.5, θ0_deg=20.0, ϕ_deg=90.0, α0_deg=0.0, pivot=0.25) =
    FlappingMotion(Float64(St), Float64(h0), Float64(θ0_deg), Float64(ϕ_deg),
                   Float64(α0_deg), Float64(pivot))

# ---------- 3. 翼型闭合轮廓与 ForwardDiff 兼容精确 SDF ----------
function profile_eval(f::NACA4, s::Float64)
    yt = 5.0 * f.t * (0.2969 * sqrt(s) - 0.1260 * s - 0.3516 * s^2 + 0.2843 * s^3 - 0.1036 * s^4)
    if f.m == 0.0 || f.p <= 0.0 || f.p >= 1.0
        return 0.0, 0.0, yt
    elseif s < f.p
        yc  = f.m / f.p^2 * (2.0 * f.p * s - s^2)
        dyc = 2.0 * f.m / f.p^2 * (f.p - s)
        return yc, dyc, yt
    else
        yc  = f.m / (1.0 - f.p)^2 * ((1.0 - 2.0 * f.p) + 2.0 * f.p * s - s^2)
        dyc = 2.0 * f.m / (1.0 - f.p)^2 * (f.p - s)
        return yc, dyc, yt
    end
end

function profile_eval(f::CustomFoil, s::Float64)
    yc  = Float64(f.yc(s))
    yt  = 0.5 * max(Float64(f.yt(s)), 0.0)
    ds  = 1e-4
    s1, s2 = max(0.0, s - ds), min(1.0, s + ds)
    dyc = (Float64(f.yc(s2)) - Float64(f.yc(s1))) / (s2 - s1)
    return yc, dyc, yt
end

const N_SIDE = 24
const N_PTS  = 2 * N_SIDE

function build_polygon(foil::AbstractFoil, L::Real; pivot::Float64=0.25)
    ss = [0.5 * (1 - cos(π * k / N_SIDE)) for k in 0:N_SIDE]
    upper = Vector{SVector{2,Float32}}(undef, length(ss))
    lower = Vector{SVector{2,Float32}}(undef, length(ss))
    for (k, s) in enumerate(ss)
        yc, dyc, yt = profile_eval(foil, s)
        ϕ = atan(dyc)
        upper[k] = SVector{2,Float32}((s - yt * sin(ϕ) - pivot) * L, (yc + yt * cos(ϕ)) * L)
        lower[k] = SVector{2,Float32}((s + yt * sin(ϕ) - pivot) * L, (yc - yt * cos(ϕ)) * L)
    end
    pts_vec = vcat(reverse(upper), lower[2:end-1])
    pts = SVector{N_PTS,SVector{2,Float32}}(pts_vec)
    xmin = minimum(p -> p[1], pts)
    xmax = maximum(p -> p[1], pts)
    ymin = minimum(p -> p[2], pts)
    ymax = maximum(p -> p[2], pts)
    return pts, (xmin, xmax, ymin, ymax)
end

# 带包围盒快速剪枝的精确多边形 SDF（全 isbits，兼容 CPU/GPU 及 ForwardDiff）
function polygon_sdf(pts::SVector{N,SVector{2,Float32}}, bbox::NTuple{4,Float32}, x) where {N}
    T = eltype(x)
    xmin, xmax, ymin, ymax = bbox
    dx_box = max(xmin - x[1], zero(T), x[1] - xmax)
    dy_box = max(ymin - x[2], zero(T), x[2] - ymax)
    d2_box = dx_box * dx_box + dy_box * dy_box
    if d2_box > 16f0
        return sqrt(d2_box)
    end

    d2 = zero(T) + Inf32
    inside = false
    n = length(pts)
    j = n
    @inbounds for i in 1:n
        a = pts[j]
        b = pts[i]
        ab = b - a
        ax = x - a
        denom = ab[1] * ab[1] + ab[2] * ab[2]
        s = denom > 0f0 ? clamp((ax[1] * ab[1] + ax[2] * ab[2]) / denom, zero(T), one(T)) : zero(T)
        rx = x[1] - (a[1] + s * ab[1])
        ry = x[2] - (a[2] + s * ab[2])
        d2 = min(d2, rx * rx + ry * ry)
        if ((a[2] > x[2]) != (b[2] > x[2])) &&
           (x[1] < (b[1] - a[1]) * (x[2] - a[2]) / (b[2] - a[2]) + a[1])
            inside = !inside
        end
        j = i
    end
    return (inside ? -one(T) : one(T)) * sqrt(d2 + 1f-12)
end

# ---------- 4. 运动坐标映射 ----------
function make_motion_map(m::StaticMotion, L::Real, U::Real, center)
    α = deg2rad(m.α_deg)
    c, s = Float32(cos(α)), Float32(sin(α))
    x0, y0 = Float32(center[1]), Float32(center[2])
    return (x, t) -> SA[c * (x[1] - x0) - s * (x[2] - y0),
                        s * (x[1] - x0) + c * (x[2] - y0)]
end

function flapping_omega(m::FlappingMotion, L::Real, U::Real)
    if m.h0 > 0.0
        return π * m.St * U / (m.h0 * L)   # St = f*(2*h0*L)/U => ω = 2πf = π*St*U/(h0*L)
    else
        return 2π * m.St * U / L           # 纯俯仰退化为缩减频率 f*L/U = St
    end
end

function make_motion_map(m::FlappingMotion, L::Real, U::Real, center)
    h0 = Float32(m.h0 * L)
    ω  = Float32(flapping_omega(m, L, U))
    θ0 = Float32(deg2rad(m.θ0_deg))
    α0 = Float32(deg2rad(m.α0_deg))
    ϕ  = Float32(deg2rad(m.ϕ_deg))
    x0, y0 = Float32(center[1]), Float32(center[2])
    return (x, t) -> begin
        yh = h0 * sin(ω * t)
        θ  = α0 + θ0 * sin(ω * t + ϕ)
        c, s = cos(θ), sin(θ)
        dx = x[1] - x0
        dy = x[2] - (y0 + yh)
        SA[c * dx - s * dy, s * dx + c * dy]
    end
end

# 自动将计算域取整到 32 的倍数，保证 WaterLily 多重网格效率
domain_dims(L::Int, m::StaticMotion)   = (cld(6 * L, 32) * 32, cld(4 * L, 32) * 32)
domain_dims(L::Int, m::FlappingMotion) = (cld(6 * L, 32) * 32, cld(max(4 * L, round(Int, (3.0 + 3.0 * m.h0) * L)), 32) * 32)

# ---------- 5. 流场可视化工具（涡量场 + 翼型实时轮廓 + 升阻力曲线） ----------
function body_world_polygon(pts::SVector{N,SVector{2,Float32}},
                            motion::StaticMotion, L::Real, U::Real,
                            center, t_raw::Real) where {N}
    α = deg2rad(motion.α_deg)
    c, s = cos(α), sin(α)
    x0, y0 = Float64(center[1]), Float64(center[2])
    xs = Vector{Float64}(undef, N)
    ys = Vector{Float64}(undef, N)
    @inbounds for i in 1:N
        px, py = Float64(pts[i][1]), Float64(pts[i][2])
        # map 为 R(+α)(x - c)，故逆变换（物体 -> 世界）为 c + R(-α) p
        xs[i] = (x0 + c * px + s * py) / L
        ys[i] = (y0 - s * px + c * py) / L
    end
    return Shape(xs, ys)
end

function body_world_polygon(pts::SVector{N,SVector{2,Float32}},
                            motion::FlappingMotion, L::Real, U::Real,
                            center, t_raw::Real) where {N}
    h0 = motion.h0 * L
    ω  = flapping_omega(motion, L, U)
    yh = h0 * sin(ω * t_raw)
    θ  = deg2rad(motion.α0_deg) + deg2rad(motion.θ0_deg) * sin(ω * t_raw + deg2rad(motion.ϕ_deg))
    c, s = cos(θ), sin(θ)
    x0, y0 = Float64(center[1]), Float64(center[2]) + yh
    xs = Vector{Float64}(undef, N)
    ys = Vector{Float64}(undef, N)
    @inbounds for i in 1:N
        px, py = Float64(pts[i][1]), Float64(pts[i][2])
        xs[i] = (x0 + c * px + s * py) / L
        ys[i] = (y0 - s * px + c * py) / L
    end
    return Shape(xs, ys)
end

function compute_vorticity(sim)
    WaterLily.@inside sim.flow.σ[I] = WaterLily.curl(3, I, sim.flow.u) * sim.L / sim.U
    return Array(sim.flow.σ)[2:end-1, 2:end-1]
end

function make_vorticity_plot(ω, xs, ys, foil_shape, title_str;
                             clims=(-8.0, 8.0), show_cbar=true)
    p = heatmap(xs, ys, transpose(clamp.(ω, clims[1], clims[2]));
                c=:bwr, clims=clims, aspect_ratio=:equal,
                xlims=(first(xs), last(xs)), ylims=(first(ys), last(ys)),
                xlabel="x / L", ylabel="y / L", title=title_str,
                colorbar=show_cbar, colorbar_title=show_cbar ? "ωL/U" : "",
                framestyle=:box, titlefontsize=10, guidefontsize=9)
    plot!(p, foil_shape; fillcolor=:gray20, linecolor=:black, linewidth=1.2, label="")
    return p
end

function make_summary_plot(last_flow_plt, ts, cls, cds, is_flapping, t_avg_val)
    if is_flapping
        pf = plot(ts, -cds; lw=1.8, label="Ct = -Cd", color=:crimson,
                  xlabel="t* = tU/L", ylabel="Force coeff.", title="Thrust & Lift History",
                  titlefontsize=10, guidefontsize=9, legend=:topright)
        plot!(pf, ts, cls; lw=1.4, ls=:dash, label="Cl", color=:royalblue)
        hline!(pf, [0.0]; lw=0.8, ls=:dot, color=:gray, label="")
    else
        pf = plot(ts, cls; lw=1.8, label="Cl", color=:royalblue,
                  xlabel="t* = tU/L", ylabel="Force coeff.", title="Lift & Drag History",
                  titlefontsize=10, guidefontsize=9, legend=:topright)
        plot!(pf, ts, cds; lw=1.6, label="Cd", color=:darkorange)
    end
    vline!(pf, [t_avg_val]; lw=1.0, ls=:dot, color=:black, label="avg start")
    return plot(last_flow_plt, pf; layout=(2, 1), size=(760, 620), margin=4Plots.mm)
end

# ---------- 6. 统一仿真入口 ----------
"""
    run_sim(foil; motion=StaticMotion(15.0), Re=1000.0, L=32,
            t_end=nothing, t_avg=nothing,
            viz=:live, save_prefix="flow", plot_every=1, verbose=true)

运行一次 WaterLily 2D 翼型仿真并可选展示/保存流场变化：
- `viz` 可选：
  - `:live`      —— 边算边实时显示涡量场，结束后保存 `"\$(save_prefix)_summary.png"`
  - `:gif`       —— 离线录制动画 `"\$(save_prefix).gif"` 并保存汇总图（慢电脑/插 PPT 推荐）
  - `:snapshots` —— 只在 4 个关键时刻抓帧拼成 2×2 演进图 `"\$(save_prefix)_snapshots.png"`（最快）
  - `:none`      —— 关闭绘图，全速数值计算（第 3 讲优化搜索默认）
- 返回 NamedTuple：`Cl`, `Cd`, `Ct` (`-Cd`), `LD` (`Cl/Cd`), `Cp_heave`, `η_heave`, `ts`, `cls`, `cds`, `sim`
"""
function run_sim(foil::AbstractFoil;
                 motion::AbstractMotion = StaticMotion(15.0),
                 Re::Real = 1000.0,
                 L::Int = 32,
                 t_end::Union{Nothing,Real} = nothing,
                 t_avg::Union{Nothing,Real} = nothing,
                 viz::Symbol = :live,
                 save_prefix::AbstractString = "flow",
                 plot_every::Int = 1,
                 verbose::Bool = true)
    if foil isa NACA4 && foil.t < 2.0 / L && verbose
        @warn "翼型厚度 t=$(foil.t) 在 L=$L 下不足 2 个网格，建议保持 t >= $(round(2.0/L, digits=3))。"
    end

    U = 1.0
    nx, ny = domain_dims(L, motion)
    center = (Float32(1.8L), Float32(ny / 2))

    pts, bbox = build_polygon(foil, L; pivot=motion.pivot)
    body = AutoBody((x, t) -> polygon_sdf(pts, bbox, x),
                    make_motion_map(motion, L, U, center))
    sim = Simulation((nx, ny), (U, 0.0), L; ν=U * L / Re, body=body)

    is_flapping = motion isa FlappingMotion
    if is_flapping
        T_cyc = motion.h0 > 0 ? (2 * motion.h0 / max(motion.St, 1e-3)) : (1.0 / max(motion.St, 1e-3))
        t_end_val = isnothing(t_end) ? 4.0 * T_cyc : Float64(t_end)
        t_avg_val = isnothing(t_avg) ? 2.0 * T_cyc : Float64(t_avg)
        dt_samp   = T_cyc / 20.0
        ω         = flapping_omega(motion, L, U)
        h0_grid   = motion.h0 * L
    else
        t_end_val = isnothing(t_end) ? 8.0 : Float64(t_end)
        t_avg_val = isnothing(t_avg) ? 0.5 * t_end_val : Float64(t_avg)
        dt_samp   = 0.2
        ω         = 0.0
        h0_grid   = 0.0
    end

    ts   = Float64[]
    cds  = Float64[]
    cls  = Float64[]
    cps  = Float64[]

    t_grid_steps = collect(dt_samp:dt_samp:t_end_val)
    n_steps = length(t_grid_steps)

    # WaterLily 网格单元中心位于 (ix - 0.5, iy - 0.5)
    xs = ((1:nx) .- 0.5) ./ L
    ys = ((1:ny) .- 0.5) ./ L

    anim = viz == :gif ? Animation() : nothing
    snap_plots = Plots.Plot[]
    snap_indices = if viz == :snapshots
        if is_flapping
            # 取最后一个周期内的 4 个等距相位（0, T/4, T/2, 3T/4）
            Set(clamp.(round.(Int, range(max(1, n_steps - 19), n_steps, length=4)), 1, n_steps))
        else
            Set(clamp.(round.(Int, range(max(1, round(Int, 0.2 * n_steps)), n_steps, length=4)), 1, n_steps))
        end
    else
        Set{Int}()
    end
    last_flow_plt = nothing

    for (step_idx, t_star) in enumerate(t_grid_steps)
        sim_step!(sim, t_star; remeasure=is_flapping)
        # WaterLily total_force 为物体对流体的作用力，取负号得流体作用于翼型的阻力/升力
        F  = -WaterLily.total_force(sim) ./ (0.5 * U^2 * L)
        cd = Float64(F[1])
        cl = Float64(F[2])
        push!(ts, t_star)
        push!(cds, cd)
        push!(cls, cl)

        t_raw = WaterLily.sim_time(sim) * L / U
        if is_flapping
            y_dot = h0_grid * ω * cos(ω * t_raw)
            push!(cps, -cl * (y_dot / U))   # 沉浮输入功率系数 Cp_heave = -Fy * ẏ / (0.5 U^3 L)
        end

        need_plot = (viz == :live && (step_idx % plot_every == 0 || step_idx == n_steps)) ||
                    (viz == :gif  && (step_idx % plot_every == 0 || step_idx == n_steps)) ||
                    (viz == :snapshots && (step_idx in snap_indices || step_idx == n_steps))

        if need_plot
            ω_field = compute_vorticity(sim)
            foil_sh = body_world_polygon(pts, motion, L, U, center, t_raw)
            t_lbl = is_flapping ?
                "t*=$(round(t_star, digits=2)) | Ct=$(round(-cd, digits=2)), Cl=$(round(cl, digits=2))" :
                "t*=$(round(t_star, digits=2)) | Cl=$(round(cl, digits=2)), Cd=$(round(cd, digits=2))"
            plt = make_vorticity_plot(ω_field, xs, ys, foil_sh, t_lbl;
                                      show_cbar=(viz != :snapshots))
            last_flow_plt = plt
            if viz == :live
                display(plt)
            elseif viz == :gif
                frame(anim, plt)
            elseif viz == :snapshots && (step_idx in snap_indices)
                push!(snap_plots, plt)
            end
        end
    end

    mask = ts .>= t_avg_val
    Cd_mean = mean(cds[mask])
    Cl_mean = mean(cls[mask])
    Ct_mean = -Cd_mean
    LD_mean = Cl_mean / max(Cd_mean, 1e-6)

    Cp_mean = is_flapping ? mean(cps[mask]) : NaN
    η_mean  = (is_flapping && Ct_mean > 0 && Cp_mean > 1e-6) ? (Ct_mean / Cp_mean) : NaN

    if viz != :none && !isnothing(last_flow_plt)
        summary_path = "$(save_prefix)_summary.png"
        summary_plt = make_summary_plot(last_flow_plt, ts, cls, cds, is_flapping, t_avg_val)
        savefig(summary_plt, summary_path)
        if viz == :gif
            gif_path = "$(save_prefix).gif"
            gif(anim, gif_path; fps=12, show_msg=false)
            verbose && println("  已保存流场动图: $(abspath(gif_path))")
        elseif viz == :snapshots && !isempty(snap_plots)
            snap_path = "$(save_prefix)_snapshots.png"
            snap_grid = plot(snap_plots...; layout=(2, 2), size=(920, 620), margin=3Plots.mm)
            savefig(snap_grid, snap_path)
            verbose && println("  已保存 4 时刻演进图: $(abspath(snap_path))")
        end
        verbose && println("  已保存汇总图: $(abspath(summary_path))")
    end

    if verbose
        if is_flapping
            println("扑翼结果 (St=$(motion.St), h0=$(motion.h0), θ0=$(motion.θ0_deg)°, ϕ=$(motion.ϕ_deg)°, L=$L):")
            println("  平均推力系数 Ct = $(round(Ct_mean, digits=3)) | 平均升力系数 Cl = $(round(Cl_mean, digits=3)) | 沉浮功率 Cp = $(round(Cp_mean, digits=3)) | 推进效率 η ≈ $(round(η_mean, digits=3))")
        else
            println("翼型结果 (Re=$(Int(Re)), α=$(motion.α_deg)°, L=$L):")
            println("  平均升力系数 Cl = $(round(Cl_mean, digits=3)) | 平均阻力系数 Cd = $(round(Cd_mean, digits=3)) | 升阻比 Cl/Cd = $(round(LD_mean, digits=3))")
        end
    end

    return (Cl=Cl_mean, Cd=Cd_mean, Ct=Ct_mean, LD=LD_mean,
            Cp_heave=Cp_mean, η_heave=η_mean,
            ts=ts, cls=cls, cds=cds, sim=sim)
end

# ---------- 6. 第 3 讲优化算法专用黑盒打分接口 ----------
"""
    evaluate_airfoil(x; metric=:LD, Re=1000.0, α_deg=15.0, L=24,
                     bounds=((0.0, 0.14), (0.15, 0.80), (0.08, 0.22)))

供第 3 讲优化算法直接调用的纯函数接口：
- 输入 `x = [m, p, t]`
- 返回越大越好的标量分数（越界自动返回惩罚值 `-1e3`）
- `metric` 可选 `:LD`（升阻比 `Cl/Cd`）或 `:Cl`（升力系数）
"""
function evaluate_airfoil(x::AbstractVector;
                          metric::Symbol = :LD,
                          Re::Real = 1000.0,
                          α_deg::Real = 15.0,
                          L::Int = 24,
                          t_end::Real = 6.0,
                          t_avg::Real = 3.0,
                          bounds = ((0.0, 0.14), (0.15, 0.80), (0.08, 0.22)))
    m, p, t = Float64(x[1]), Float64(x[2]), Float64(x[3])
    # 越界软惩罚（确保优化器留在物理合理且网格可解析的区域内）
    penalty = 0.0
    for (val, (lo, hi)) in zip((m, p, t), bounds)
        if val < lo
            penalty += (lo - val)^2
        elseif val > hi
            penalty += (val - hi)^2
        end
    end
    if penalty > 0.0
        return -10.0 - 1000.0 * penalty
    end

    res = run_sim(NACA4(m, p, t); motion=StaticMotion(α_deg),
                  Re=Re, L=L, t_end=t_end, t_avg=t_avg, viz=:none, verbose=false)
    return metric == :Cl ? res.Cl : res.LD
end

end # module FoilLab
