/**
 * Tabela 9 — Cpe para telhados com duas águas, simétricos, de calha
 * central, em edificações de planta retangular (NBR 6123:2023).
 *
 * Inclui zona EF, GH, EG, FH.
 *
 * Fonte: NBR 6123:2023, p. 23 (Tabela 9).
 * Última auditoria: 2026-07-08 — valores exatos do PDF implementados.
 */

import { bilinearInterp } from '../bilinear-interp';


export interface ValleyRoofCpe {
  EF: number;
  GH: number;
  EG: number;
  FH: number;
}

// Para h/b = 0.5 (ou interpolar depois se a norma der mais, mas a tabela só dá h/b = 0.5)
// a/b = 1 e a/b = 2.
// h'/h <= 0.05 e h'/h de 0.1 a 0.2

const AB = [1, 2] as const;
const H_LINE_H = [0.05, 0.15] as const; // 0.1 a 0.2 usamos o médio 0.15 para interpolar ou apenas limite

const T9_DATA = {
  1: {
    0.05: { EF: -0.6, GH: -0.2, EG: -0.7, FH: -0.1 },
    0.15: { EF: -0.7, GH: -0.4, EG: -0.7, FH: -0.3 }, // 0.1 a 0.2
  },
  2: {
    0.05: { EF: -0.8, GH: -0.3, EG: -0.4, FH: +0.2 },
    0.15: { EF: -0.8, GH: -0.5, EG: -0.5, FH: +0.2 },
  }
};

function interpVal(ab: number, hLineH: number, key: keyof ValleyRoofCpe): number {
  const abClamped = Math.max(1, Math.min(2, ab));
  const hlClamped = Math.max(0.05, Math.min(0.15, hLineH));

  const grid = {
    xs: AB,
    ys: H_LINE_H,
    values: [
      [T9_DATA[1][0.05][key], T9_DATA[2][0.05][key]],
      [T9_DATA[1][0.15][key], T9_DATA[2][0.15][key]]
    ]
  };

  return Number(bilinearInterp(grid, abClamped, hlClamped).toFixed(2));
}

export function getValleyRoofCpeNBR6123(a: number, b: number, h: number, hLine: number): ValleyRoofCpe {
  const ab = a / Math.max(b, 0.001);
  const hLineH = hLine / Math.max(h, 0.001);
  return {
    EF: interpVal(ab, hLineH, 'EF'),
    GH: interpVal(ab, hLineH, 'GH'),
    EG: interpVal(ab, hLineH, 'EG'),
    FH: interpVal(ab, hLineH, 'FH'),
  };
}