import csv
import re

I = 45.0  # A

def parse_rds(s):
    m = re.match(r'([\d.]+)\s*mOhm', s)
    if m:
        return float(m.group(1)) * 1e-3
    return None

def parse_price(s):
    try:
        return float(s)
    except:
        return None

results = []

with open(r'C:\Users\janik\Downloads\single_fets__mosfets.csv', 'r', encoding='utf-8-sig') as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        if len(row) < 25:
            continue
        part = row[3].strip()
        mfr = row[4].strip()
        price = parse_price(row[8].strip())
        vdss = row[16].strip()
        rds_str = row[19].strip()
        qg_str = row[21].strip()
        pkg = row[30].strip()
        rds = parse_rds(rds_str)
        if rds is None:
            continue
        p_cond = I * I * rds
        # Extract Qg for reference
        m = re.match(r'([\d.]+)\s*nC', qg_str)
        qg_nc = float(m.group(1)) if m else 0
        fom = price * rds * 1e3  # $ * mOhm
        results.append({
            'part': part,
            'mfr': mfr,
            'vdss': vdss,
            'rds_mohm': rds * 1e3,
            'p_cond': p_cond,
            'price': price,
            'fom': fom,
            'pkg': pkg,
        })

results.sort(key=lambda x: x['fom'])

print(f"MOSFET FOM = Price($) x Rds(on)(mOhm)  [lower is better]  |  P_cond @ {I:.0f}A")
print(f"{'='*115}")
print(f"{'#':>3} {'Part Number':<28} {'Mfr':<15} {'Vdss':>6} {'Rds':>7} {'Price':>7} {'FOM':>8} {'P_cond':>7} {'Package':<20}")
print(f"{'':>3} {'':28} {'':15} {'':>6} {'mOhm':>7} {'$':>7} {'$*mOhm':>8} {'W':>7}")
print(f"{'-'*115}")

for i, r in enumerate(results):
    print(f"{i+1:>3} {r['part']:<28} {r['mfr']:<15} {r['vdss']:>6} {r['rds_mohm']:>7.2f} {r['price']:>7.2f} {r['fom']:>8.2f} {r['p_cond']:>7.2f} {r['pkg']:<20}")
