import assert from 'node:assert/strict';

const E = 70e9;
const POISSON = 0.3;
const COLUMN_WIDTH_MM = 30;
const SP_COEFFICIENT = 0.901;
const SP_EXPONENT_DIVISOR = 16;
const CLASSICAL_COEFFICIENT = 0.605;

const tests = [
  { id: 'W1', rt: 333, gamma: 0.886 },
  { id: 'W2', rt: 333, gamma: 0.887 },
  { id: 'W3', rt: 333, gamma: 0.633 },
  { id: 'W4', rt: 333, gamma: 0.645 },
  { id: 'W5', rt: 333, gamma: 0.569 },
];

function close(actual, expected, tolerance = 1e-12, label = 'value') {
  assert.ok(
    Math.abs(actual - expected) <= tolerance,
    `${label}: expected ${expected}, received ${actual}`,
  );
}

function columnSecondMomentMm4(widthMm, thicknessMm) {
  return widthMm * thicknessMm ** 3 / 12;
}

function eulerLoad({ modulusPa, secondMomentMm4, lengthM, effectiveLengthFactor }) {
  const secondMomentM4 = secondMomentMm4 * 1e-12;
  const effectiveLengthM = effectiveLengthFactor * lengthM;
  return Math.PI ** 2 * modulusPa * secondMomentM4 / effectiveLengthM ** 2;
}

function classicalCylinderStressPa({ modulusPa, radiusThicknessRatio }) {
  return CLASSICAL_COEFFICIENT * modulusPa / radiusThicknessRatio;
}

function sp8007Gamma(radiusThicknessRatio) {
  const phi = Math.sqrt(radiusThicknessRatio) / SP_EXPONENT_DIVISOR;
  return 1 - SP_COEFFICIENT * (1 - Math.exp(-phi));
}

function koiterAlpha(poisson) {
  return 0.75 * Math.sqrt(3 * (1 - poisson ** 2));
}

function koiterGamma({ epsilon, poisson }) {
  if (epsilon === 0) return 1;
  const alpha = koiterAlpha(poisson);
  return 1 + alpha * epsilon -
    Math.sqrt(alpha * epsilon * (2 + alpha * epsilon));
}

function rounded(value, places) {
  return Number(value.toFixed(places));
}

const secondMomentMm4 = columnSecondMomentMm4(COLUMN_WIDTH_MM, 3);
const defaultColumnLoadN = eulerLoad({
  modulusPa: E,
  secondMomentMm4,
  lengthM: 1,
  effectiveLengthFactor: 1,
});

close(secondMomentMm4, 67.5, 1e-12, 'default column I');
close(defaultColumnLoadN, 46.63388079514721, 1e-12, 'default Euler load');
assert.equal(rounded(defaultColumnLoadN, 2), 46.63);

const defaultRt = 500;
const defaultPhi = Math.sqrt(defaultRt) / SP_EXPONENT_DIVISOR;
const defaultGamma = sp8007Gamma(defaultRt);
const defaultClassicalMpa = classicalCylinderStressPa({
  modulusPa: E,
  radiusThicknessRatio: defaultRt,
}) / 1e6;
const defaultDesignMpa = defaultGamma * defaultClassicalMpa;
const defaultOverprediction = 1 / defaultGamma;

close(defaultPhi, 1.3975424859373686, 1e-15, 'default phi');
close(defaultGamma, 0.32173055595873434, 1e-15, 'default SP gamma');
close(defaultClassicalMpa, 84.7, 1e-12, 'default classical stress MPa');
close(defaultDesignMpa, 27.2505780897048, 1e-12, 'default design stress MPa');
close(defaultOverprediction, 3.1081909426354315, 1e-14, 'default theory ratio');
assert.equal(rounded(defaultGamma, 3), 0.322);
assert.equal(rounded(defaultClassicalMpa, 2), 84.7);
assert.equal(rounded(defaultDesignMpa, 2), 27.25);
assert.equal(rounded(defaultOverprediction, 2), 3.11);

const rangeRatios = [50, 100, 200, 300, 500, 800, 1000, 1490, 1500];
const range = rangeRatios.map((rt) => {
  const gamma = sp8007Gamma(rt);
  const classicalMpa = classicalCylinderStressPa({
    modulusPa: E,
    radiusThicknessRatio: rt,
  }) / 1e6;
  return {
    rt,
    phi: Math.sqrt(rt) / SP_EXPONENT_DIVISOR,
    gamma,
    classicalMpa,
    designMpa: gamma * classicalMpa,
    theoryRatio: 1 / gamma,
  };
});

for (let index = 1; index < range.length; index += 1) {
  assert.ok(
    range[index].gamma < range[index - 1].gamma,
    `SP gamma must decrease over the checked R/t range at index ${index}`,
  );
}

assert.ok(sp8007Gamma(300) > 0.4 && sp8007Gamma(300) < 0.41);
assert.ok(sp8007Gamma(500) > 0.32 && sp8007Gamma(500) < 0.33);
assert.ok(sp8007Gamma(1000) > 0.22 && sp8007Gamma(1000) < 0.23);
assert.ok(sp8007Gamma(1500) > 0.17 && sp8007Gamma(1500) < 0.18);
assert.ok(1 / sp8007Gamma(300) > 2);
assert.ok(1 / sp8007Gamma(500) > 3);

const alpha = koiterAlpha(POISSON);
const koiterCases = [0, 0.01, 0.02, 0.05, 0.1, 0.25, 0.5, 1].map(
  (epsilon) => ({
    epsilon,
    gamma: koiterGamma({ epsilon, poisson: POISSON }),
  }),
);

close(alpha, 1.239203373139373, 1e-15, 'Koiter alpha');
close(koiterCases[0].gamma, 1, 0, 'perfect Koiter shell');
close(
  koiterGamma({ epsilon: 0.1, poisson: POISSON }),
  0.6108931210496589,
  1e-15,
  'default Koiter gamma',
);
assert.equal(
  rounded(100 * (1 - koiterGamma({ epsilon: 0.1, poisson: POISSON })), 1),
  38.9,
);
assert.equal(
  rounded(koiterGamma({ epsilon: 1, poisson: POISSON }), 3),
  0.236,
);

for (let index = 1; index < koiterCases.length; index += 1) {
  assert.ok(
    koiterCases[index].gamma < koiterCases[index - 1].gamma,
    `Koiter gamma must decrease with epsilon at index ${index}`,
  );
}

const testGammaSum = tests.reduce((sum, point) => sum + point.gamma, 0);
const testMinimum = Math.min(...tests.map((point) => point.gamma));
const testMaximum = Math.max(...tests.map((point) => point.gamma));
const testMean = testGammaSum / tests.length;

close(testGammaSum, 3.62, 1e-12, 'published test checksum');
close(testMinimum, 0.569, 1e-12, 'published test minimum');
close(testMaximum, 0.887, 1e-12, 'published test maximum');
close(testMean, 0.724, 1e-12, 'published test mean');
assert.equal(tests.every((point) => point.rt === 333), true);

console.log('PASS: independent shell-buckling verifier');
console.log('');
console.log('Default live column');
console.log(`  I = ${secondMomentMm4.toFixed(2)} mm^4`);
console.log(`  Euler Pcr = ${defaultColumnLoadN.toFixed(6)} N`);
console.log('');
console.log('Default live shell at R/t = 500');
console.log(`  phi = ${defaultPhi.toFixed(9)}`);
console.log(`  classical stress = ${defaultClassicalMpa.toFixed(6)} MPa`);
console.log(`  SP-8007 gamma = ${defaultGamma.toFixed(9)}`);
console.log(`  knocked-down stress = ${defaultDesignMpa.toFixed(6)} MPa`);
console.log(`  theory / lower bound = ${defaultOverprediction.toFixed(6)}x`);
console.log('');
console.log('SP-8007 range sweep');
for (const row of range) {
  console.log(
    `  R/t ${String(row.rt).padStart(4)}: gamma ${row.gamma.toFixed(6)}, ` +
    `classical ${row.classicalMpa.toFixed(3)} MPa, ` +
    `design ${row.designMpa.toFixed(3)} MPa, ratio ${row.theoryRatio.toFixed(3)}x`,
  );
}
console.log('');
console.log(`Koiter alpha at nu = 0.3: ${alpha.toFixed(9)}`);
console.log('Koiter imperfection sweep');
for (const row of koiterCases) {
  console.log(
    `  epsilon ${row.epsilon.toFixed(2)}: gamma ${row.gamma.toFixed(6)}, ` +
    `load lost ${(100 * (1 - row.gamma)).toFixed(3)}%`,
  );
}
console.log('');
console.log('Published five-test cross-check at R/t about 333');
console.log(`  factors = ${tests.map((point) => point.gamma.toFixed(3)).join(', ')}`);
console.log(
  `  min ${testMinimum.toFixed(3)}, max ${testMaximum.toFixed(3)}, ` +
  `mean ${testMean.toFixed(3)}, checksum ${testGammaSum.toFixed(3)}`,
);
console.log('');
console.log('All assertions passed.');
