import sys
import os

# Set up logging to file
f = open("debug_log_v2.txt", "w", encoding="utf-8")
def log(msg):
    print(msg)
    f.write(str(msg) + "\n")

sys.path.append(os.getcwd())
try:
    from app.models import SessionLocal, OrderRecord
    from app.services.fuzzy_matcher import normalize_pn_for_matching, normalize_customer_name
except ImportError as e:
    log(f"Import Error: {e}")
    sys.exit(1)

pn1 = "PSMQC098N10LS2-AU_R2_002A1" 
target_norm = normalize_pn_for_matching(pn1)

db = SessionLocal()
log("--- Searching Orders for SEMISALES (or PN match) ---")

orders = db.query(OrderRecord).all()
found = []
for o in orders:
    # Check customer name (fuzzy) or PN
    norm_cust = normalize_customer_name(o.customer or "")
    norm_pn = normalize_pn_for_matching(o.pn or "")
    
    if "SEMISALES" in norm_cust or norm_pn == target_norm:
        found.append(o)

log(f"Found {len(found)} orders:")
for o in found:
    norm_o_pn = normalize_pn_for_matching(o.pn)
    match_mark = "[MATCH PN]" if norm_o_pn == target_norm else "[NO MATCH]"
    log(f"ID: {o.id}, OrderID: {o.order_id}, OrderNo: {o.order_no}, Date: {o.date}, Qty: {o.qty}, PN: {o.pn}, Cust: {o.customer} {match_mark}")

log("--- Done ---")
f.close()
db.close()
