import re
from typing import Dict, List, Any

# 1. UNIVERSAL GRAMMAR OF EVASION (DECEPTIVE MARKETING NARRATIVES)
EVASION_PATTERNS = {
"Subjective Gatekeeping & Authority Appeals": [
r"\b(?:industry[- ]standard|professional[- ]grade|commercial[- ]grade)\b",
r"\b(?:artisan|heritage|master[- ]crafted|hand[- ]inspected|shop[- ]tested)\b",
r"\b(?:luthier[- ]approved|machinist[- ]grade|military[- ]spec)\b",
r"\b(?:proprietary|custom[- ]engineered|secret[- ]formula)\b"
],
"Uncertified Material / Strength Claims": [
r"\b(?:aircraft[- ]grade|space[- ]age|heavy[- ]duty|ultra[- ]durable)\b",
r"\b(?:precision[- ](?:ground|machined|cut|engineered))\b",
r"\b(?:specially[- ](?:hardened|treated|tempered))\b",
r"\b(?:heavy[- ]gauge|solid[- ]feel|rigid[- ]frame)\b"
],
"Origin Masking & Geographic Framing": [
r"\bdesigned in\s+[A-Z][a-zA-Z]*(?:\s+[A-Z][a-zA-Z]*)*\b",
r"\bengineered in\s+[A-Z][a-zA-Z]*(?:\s+[A-Z][a-zA-Z]*)*\b",
r"\bfrom our\s+[a-zA-Z]+\s+shop\b",
r"\bassembled in\s+[A-Z][a-zA-Z]*(?:\s+[A-Z][a-zA-Z]*)*\b"
],
"Unsubstantiated Performance Hedging": [
r"\bup to\s+\d+(?:\.\d+)?",
r"\bas fast as\b",
r"\bvirtually\s+[a-zA-Z]+\b",
r"\beffortlessly\b",
r"\beliminates\s+[a-zA-Z\s]+?drift\b"
]
}

# 2. OBJECTIVE MECHANICAL SPECIFICATIONS (METROLOGY & MOTION TAXONOMY)
HARDWARE_ATTRIBUTES = {
"Drive System": {
"Precision Ball Screws": (r"\bball\s*screws?\b|\bsfu\d{4}\b", 30),
"Lead Screws": (r"\blead\s*screws?|acme\s*screws?|t8\s*leadscrew\b", 10),
"Rubber Timing Belts": (r"\b(?:timing\s*)?belts?|gt2\s*belt\b", -15)
},
"Guide Geometry": {
"Dual Linear Guide Rails": (r"\blinear\s*(?:guide\s*)?rails?|mgn\d+|hgr\d+\b", 30),
"Supported Hardened Rods": (r"\bsupported\s*rails?|sbr\d+\b", 15),
"V-Slot Delrin Wheels": (r"\bv[- ]wheels?|delrin\s*wheels?|roller\s*bearings?\b", -20)
},
"Motor Closed-Loop Status": {
"Closed-Loop Stepper / Servo": (r"\bclosed[- ]loop\b|\bencoder\s*feedback\b|\bservo\b", 25),
"Open-Loop Stepper": (r"\bnema\s*\d{2}\b(?!.*closed[- ]loop)|\bstepper\s*motor\b", 5)
},
"Chassis Mechanics": {
"Under-bed Centerline Axis": (r"\bunderneath\s+the\s+center\b|\bcenterline\s+stability\b|\bcenter[- ]mounted\b", 20),
"Milled Solid Plate Construction": (r"\b6061[- ]t6\b|\bcast\s*iron\b|\bsolid\s*aluminum\s*alloy\s*base\b", 20),
"Extruded Thin V-Slot": (r"\b2020\s*extrusion\b|\b2040\s*extrusion\b|\bthin\s*sheet\s*metal\b", -15)
}
}

# 3. EMPIRICAL METRICS AUDIT PATTERNS
NUMERICAL_METRIC_PATTERNS = {
"Positional Accuracy / Runout": [r"±?\s*0?\.00\d+\s*(?:mm|in|inch|\"|mil)"],
"Material Grade": [r"\b(?:6061-T6|7075|D2|O1|A2|Cr-V|SK5|Cast Iron)\b"],
"Explicit Dimensions / Work Envelope": [r"\b\d{2,4}\s*(?:x|by|\*)\s*\d{2,4}(?:\s*(?:x|by|\*)\s*\d{2,4})?\s*(?:mm|cm|in|inch|\")\b"],
"Motor Output / Torque": [r"\b\d+(?:\.\d+)?\s*(?:Nm|oz[- ]in|Ncm|kg[- ]cm)\b"],
"Spindle Power / Collet Standard": [r"\b(?:ER\d{1,2}|[\d\.]+\s*(?:kW|W|HP))\b"]
}

def audit_product_text(text: str, product_name: str = "Target Unit") -> Dict[str, Any]:
narrative_flags = []
mechanical_points = 0
detected_hardware = []
detected_metrics = []
missing_specs = []

# 1. Audit Narrative Glosses
total_glosses = 0
for category, patterns in EVASION_PATTERNS.items():
category_triggers = []
for pat in patterns:
flags = 0 if category == "Origin Masking & Geographic Framing" else re.IGNORECASE
matches = re.findall(pat, text, flags)
if matches:
total_glosses += len(matches)
category_triggers.extend(matches)
if category_triggers:
narrative_flags.append({
"category": category,
"triggers": list(set(category_triggers))
})

# 2. Extract and Score Hardware Mechanics
for subsystem, variants in HARDWARE_ATTRIBUTES.items():
subsystem_matched = False
for tier_name, (pattern, score) in variants.items():
if re.search(pattern, text, re.IGNORECASE):
mechanical_points += score
detected_hardware.append(f"{subsystem}: {tier_name} ({'+' if score > 0 else ''}{score} pts)")
subsystem_matched = True
break
if not subsystem_matched:
mechanical_points -= 5

# 3. Check for Hard Numerical Tolerances
for metric_name, patterns in NUMERICAL_METRIC_PATTERNS.items():
found = False
for pat in patterns:
matches = re.findall(pat, text, re.IGNORECASE)
if matches:
detected_metrics.append(f"{metric_name}: {list(set(matches))}")
mechanical_points += 10
found = True
break
if not found:
missing_specs.append(metric_name)

return {
"product": product_name,
"score": mechanical_points - (total_glosses * 3),
"detected_hardware": detected_hardware,
"verified_metrics": detected_metrics,
"omitted_metrics": missing_specs,
"narrative_flags": narrative_flags
}

def print_ranked_leaderboard(audited_items: List[Dict[str, Any]], target_item_name: str):
# Sort strictly by score descending
ranked = sorted(audited_items, key=lambda x: x["score"], reverse=True)

print("\n" + "=" * 80)
print(f" RANKED MECHANICAL AUDIT LEADERBOARD: {target_item_name.upper()}")
print("=" * 80)
print(f"{'RANK':<6}{'PRODUCT / MODEL':<46}{'SCORE':<10}{'INTEGRITY STATUS'}")
print("-" * 80)

for idx, item in enumerate(ranked, start=1):
if item["score"] >= 80:
status = "Verified Rigidity"
elif item["score"] >= 20:
status = "Moderate / Baseline"
else:
status = "High Narrative Risk"
print(f"#{idx:<5}{item['product'][:44]:<46}{item['score']:<10}{status}")
print("-" * 80)

# Detailed itemized reports in ranked order
print("\n" + "#" * 80)
print(" DETAILED SPECIFICATION BREAKDOWN BY RANK")
print("#" * 80)

for idx, item in enumerate(ranked, start=1):
print(f"\n[RANK #{idx}] {item['product']} (Total Score: {item['score']} pts)")
print("~" * 60)

print(" [*] Confirmed Hardware Subsystems:")
if item["detected_hardware"]:
for hw in item["detected_hardware"]:
print(f" + {hw}")
else:
print(" - No verified rigid mechanisms declared.")

print(" [#] Verified Physical Specifications:")
if item["verified_metrics"]:
for m in item["verified_metrics"]:
print(f" + {m}")
else:
print(" - None detected.")

print(" [?] Undocumented Metrology (Omissions):")
if item["omitted_metrics"]:
for o in item["omitted_metrics"]:
print(f" - Missing: {o}")
else:
print(" + Complete core specification profile.")

print(" [!] Evasive Marketing Flags:")
if item["narrative_flags"]:
for flag in item["narrative_flags"]:
print(f" * {flag['category']}: {', '.join(flag['triggers'])}")
else:
print(" - Zero evasive buzzwords flagged.")
print("\n" + "=" * 80 + "\n")

if __name__ == "__main__":
print("\n" + "=" * 80)
print(" MULTI-PRODUCT SPECIFICATION SCRUBBER & RANKING ENGINE")
print("=" * 80)

target_category = input("\nWhat product or tool are you looking for? (e.g. desktop CNC router, luthier plane): ").strip()
if not target_category:
target_category = "General Hardware"

audited_products = []
product_count = 1

while True:
print(f"\n--- Entry #{product_count} ---")
p_name = input(f"Enter Product #{product_count} Name/Model (or press Enter to finish and rank): ").strip()
if not p_name:
if not audited_products:
print("No products entered. Exiting.")
break
print("\nCalculating mechanical scores and building ranked output...")
print_ranked_leaderboard(audited_products, target_category)
break

print(f"Paste description/narrative for '{p_name}'. Press Enter on an empty line when finished:")
text_lines = []
while True:
try:
line = input()
if not line and text_lines and not text_lines[-1]:
break
text_lines.append(line)
except EOFError:
break

full_text = "\n".join(text_lines).strip()
if full_text:
report = audit_product_text(full_text, product_name=p_name)
audited_products.append(report)
product_count += 1
else:
print(f"Skipped '{p_name}' (empty text).")