function main_export(mode)
%MAIN_EXPORT  导出单/双周期散射的 Ab 矩阵与 normE（OpticsFEM OutFile 格式）。
%
%   main_export()         % 默认单周期 (case_config.m)
%   main_export('single')
%   main_export('double') % 需 doublePBC_mesh.mat 或 doublePBC_mesh.dat
%
% 输出 ./OutFile_single/ 或 ./OutFile_double/：
%   Ai.txt, Aj.txt, Av.txt, Bv_real.txt, Bv_imag.txt  — PBC 投影后
%   Ex, Ey, Ez, normE
% 输出 ./OutFile_*_asm/：PBC 投影前的装配矩阵

if nargin < 1 || isempty(mode)
    mode = 'single';
end

clc;
root = fileparts(mfilename('fullpath'));

switch lower(mode)
    case 'single'
        [phy, cfg] = case_config();
        outDir = fullfile(root, 'OutFile_single');
        outAsm = fullfile(root, 'OutFile_single_asm');
        pbcFn = @assembly_pbc_single;
    case 'double'
        [phy, cfg] = case_config_doublePBC();
        outDir = fullfile(root, 'OutFile_double');
        outAsm = fullfile(root, 'OutFile_double_asm');
        pbcFn = @assembly_pbc_double;
    otherwise
        error('main_export:BadMode', 'mode 须为 ''single'' 或 ''double''。');
end

mesh = load_case_mesh(cfg, root);
mesh.incIndex = findTri(phy.inc, mesh);
mesh.outIndex = findTri(phy.out, mesh);
mesh.PBCIndex = findPBCIndex(phy.src, phy.dst, cfg.pbcWaveVec, mesh);
mesh.PBCphi = cfg.pbcPhi;

if strcmpi(mode, 'double')
    mesh.PBCIndex2 = findPBCIndex(phy.src2, phy.dst2, cfg.pbcWaveVec2, mesh);
    mesh.PBCphi2 = cfg.pbcPhi2;
end

solver.Ai = [];
solver.Aj = [];
solver.Av = [];
solver.b = zeros(mesh.NbrEdge, 1);
solver = assembly_equ(phy, mesh, solver);
solver = assembly_out(phy, mesh, solver);
solver = assembly_inc(phy, mesh, solver);
solver.A = sparse(solver.Ai, solver.Aj, solver.Av);

export_ab_matrix(solver, outAsm);

solver = pbcFn(mesh, solver);
solver.A = solver.P' * solver.A * solver.P;
solver.b = solver.P' * solver.b;

export_ab_matrix(solver, outDir);

solver.x = solver.A \ solver.b;
solver.x = solver.P * solver.x;

[Ex, Ey, Ez, normE] = get_ele_vertices(mesh, solver);
export_fields(Ex, Ey, Ez, normE, outDir);

fprintf('\n完成 [%s]。\n', mode);
fprintf('  投影后 Ab + 场 → %s\n', outDir);
fprintf('  装配 Ab（无 PBC）→ %s\n', outAsm);
end
