"""Assay Engine: Form-Factor Baseline Matching, BIS Calculation & Dynamic Price Adjustments.""" from __future__ import annotations import json from dataclasses import dataclass, field from pathlib import Path from typing import Any from .model_client import Detection @dataclass class AssayedBoard: form_factor: str board_integrity_score: float # BIS (0.0 to 100.0) base_price: float adjusted_price: float price_floor: float detected_counts: dict[str, int] expected_counts: dict[str, int] fraud_desoldered_pads: int factory_unpopulated_pads: int occluded_regions: int status_band: str # "pristine" (>=85), "partial" (50-84), "severe" (<50) discrepancy_status: str = "pass" # "pass", "advisory_flag", "critical_fraud_alert" PROFILES_FILE = Path(__file__).parent / "board_profiles.json" def load_board_profiles() -> dict: if PROFILES_FILE.exists(): with open(PROFILES_FILE, "r", encoding="utf-8") as f: return json.load(f) return {} def calculate_board_integrity_score( detections: list[Detection], form_factor: str = "desktop_atx", profiles: dict | None = None, ) -> tuple[float, dict[str, int], dict[str, int], int, int, int]: """Calculate Board Integrity Score (BIS 0-100) using form factor baselines.""" if profiles is None: profiles = load_board_profiles() profile = profiles.get(form_factor) or profiles.get("default") or { "price_floor": 0.35, "expected_components": {"cpu_socket": 1, "gold_finger": 1, "ic_chip": 3, "tantalum_capacitor": 4}, "weights": {"cpu_socket": 0.40, "gold_finger": 0.25, "ic_chip": 0.20, "tantalum_capacitor": 0.15}, } expected = profile.get("expected_components", {}) weights = profile.get("weights", {}) detected_counts: dict[str, int] = {} fraud_pads = 0 factory_pads = 0 occluded = 0 for d in detections: c = d.class_name if c == "forcibly_desoldered_pad": fraud_pads += 1 elif c == "factory_unpopulated_pad": factory_pads += 1 elif c == "occluded_region": occluded += 1 else: detected_counts[c] = detected_counts.get(c, 0) + 1 # Weighted component presence ratio weighted_score = 0.0 total_weight = sum(weights.values()) or 1.0 for cls_name, exp_num in expected.items(): if exp_num > 0: det_num = detected_counts.get(cls_name, 0) ratio = min(1.0, det_num / float(exp_num)) else: ratio = 1.0 # Class not expected on this form factor (e.g. CPU socket on GPU) w = weights.get(cls_name, 0.0) weighted_score += w * ratio # Normalize to 100 bis_raw = (weighted_score / total_weight) * 100.0 # Penalize for forcibly desoldered pads (-25 points per fraud pad) fraud_penalty = fraud_pads * 25.0 final_bis = max(0.0, min(100.0, bis_raw - fraud_penalty)) return final_bis, detected_counts, expected, fraud_pads, factory_pads, occluded def calculate_adjusted_scrap_price( bis: float, base_price: float, form_factor: str = "desktop_atx", profiles: dict | None = None, ) -> tuple[float, float]: """Calculate dynamic scrap purchase price based on category scrap grade floor: Adjusted Price = Base Price * (Floor + (1 - Floor) * (BIS / 100)) """ if profiles is None: profiles = load_board_profiles() profile = profiles.get(form_factor) or profiles.get("default") or {"price_floor": 0.35} price_floor = float(profile.get("price_floor", 0.35)) adjusted_price = base_price * (price_floor + (1.0 - price_floor) * (bis / 100.0)) return round(adjusted_price, 2), price_floor def assess_bis_discrepancy(collector_bis: float, recycler_bis: float) -> str: """Assess mid-chain cannibalization fraud discrepancy bands. < 12% BIS Drop -> pass (normal capture variance) 12-25% BIS Drop -> advisory_flag > 25% BIS Drop -> critical_fraud_alert """ bis_drop = collector_bis - recycler_bis if bis_drop < 12.0: return "pass" elif bis_drop <= 25.0: return "advisory_flag" else: return "critical_fraud_alert" def assay_pcb( detections: list[Detection], base_price: float = 100.0, form_factor: str = "desktop_atx", profiles: dict | None = None, ) -> AssayedBoard: """Complete Board Integrity Assay workflow.""" bis, det_counts, exp_counts, fraud_pads, factory_pads, occluded = calculate_board_integrity_score( detections, form_factor, profiles ) adj_price, floor = calculate_adjusted_scrap_price(bis, base_price, form_factor, profiles) if bis >= 85.0: status_band = "pristine" elif bis >= 50.0: status_band = "partial" else: status_band = "severe" return AssayedBoard( form_factor=form_factor, board_integrity_score=round(bis, 1), base_price=base_price, adjusted_price=adj_price, price_floor=floor, detected_counts=det_counts, expected_counts=exp_counts, fraud_desoldered_pads=fraud_pads, factory_unpopulated_pads=factory_pads, occluded_regions=occluded, status_band=status_band, discrepancy_status="pass", )