#include <fesa/analysis/run_solver.hpp>

#include <optional>
#include <utility>

#include <fesa/io/abaqus/parser.hpp>
#include <fesa/io/abaqus/semantic_mapper.hpp>
#include <fesa/io/hdf5/writer.hpp>

namespace fesa {

AnalysisRunResult run_solver(const AnalysisRequest& request) {
    ParseDeckResult parsed = parse_deck(request.input_path);
    if (!parsed.deck.has_value()) {
        return {false, std::nullopt, std::move(parsed.diagnostics)};
    }

    DomainBuildResult mapped = map_deck_to_domain(*parsed.deck);
    if (!mapped.domain.has_value()) {
        return {false, std::nullopt, std::move(mapped.diagnostics)};
    }

    AnalysisRunResult run = LinearStaticAnalysis{}.run(*mapped.domain);
    if (!run.succeeded || !run.results.has_value()) {
        return run;
    }

    std::vector<Diagnostic> write_diagnostics = write_hdf5(
        request.output_path, *mapped.domain, *run.results);
    if (!write_diagnostics.empty()) {
        return {false, std::nullopt, std::move(write_diagnostics)};
    }

    return run;
}

}  // namespace fesa
