"""Phaxor — Circuit Breaker Engine (Python port)"""
import math

CB_RATINGS = {
    'MCB': [6, 10, 16, 20, 25, 32, 40, 50, 63],
    'MCCB': [16, 25, 32, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800],
    'ACB': [630, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6300],
}

FUSE_RATINGS = [6, 10, 16, 20, 25, 32, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630]

def solve_circuit_breaker(inputs: dict) -> dict | None:
    """Circuit Breaker Sizing Calculator."""
    p = float(inputs.get('loadPower', 0))
    v = float(inputs.get('voltage', 0))
    phase = int(inputs.get('phase', 3))
    pf = float(inputs.get('powerFactor', 0.85))
    sf = float(inputs.get('safetyFactor', 1.25))

    if p <= 0 or v <= 0:
        return None

    pf = max(0.01, min(1.0, pf))
    sf = max(1.0, sf)

    if phase == 3:
        i_load = p / (math.sqrt(3) * v * pf)
    else:
        i_load = p / (v * pf)

    i_design = i_load * sf

    # Select Type
    if i_design <= 63:
        cb_type = 'MCB'
    elif i_design <= 800:
        cb_type = 'MCCB'
    else:
        cb_type = 'ACB'

    # Select Rating
    ratings = CB_RATINGS[cb_type]
    cb_rating = ratings[-1]
    for r in ratings:
        if r >= i_design:
            cb_rating = r
            break
            
    # Select Fuse
    fuse_rating = FUSE_RATINGS[-1]
    for r in FUSE_RATINGS:
        if r >= i_design:
            fuse_rating = r
            break
            
    # Curve
    if pf < 0.7:
        curve = 'D (Motor/Inductive)'
    elif pf < 0.9:
        curve = 'C (Motor/Mixed)'
    else:
        curve = 'B (Resistive)'

    # Breaking Cap
    breaking_ka = 10
    if cb_type == 'MCCB': breaking_ka = 36
    elif cb_type == 'ACB': breaking_ka = 65

    return {
        'loadCurrent': float(f"{i_load:.2f}"),
        'designCurrent': float(f"{i_design:.2f}"),
        'cbType': cb_type,
        'cbRating': cb_rating,
        'fuseRating': fuse_rating,
        'curve': curve,
        'breakingCapacity': breaking_ka
    }
