"""Compare local For_Web serials vs server-side serials; emit delta list."""
import os

LOCAL = r"C:\Users\guru\AppData\Local\Temp\for_web_inventory.txt"
SERVER = r"C:\Users\guru\AppData\Local\Temp\server_inventory.txt"
DELTA_OUT = r"C:\Users\guru\AppData\Local\Temp\delta_to_upload.txt"

# Load server set (case-sensitive exact; mirror what we'd POST as SerialNumber)
server = set()
with open(SERVER) as f:
    for line in f:
        s = line.strip()
        if s:
            server.add(s)

# Also load a case-insensitive lookup just to see if anything only differs by case
server_ci = {s.lower() for s in server}

# Walk local inventory
local_total = 0
local_sns = set()
path_by_sn = {}
with open(LOCAL) as f:
    for line in f:
        parts = line.rstrip("\n").split("|")
        if len(parts) < 4:
            continue
        full, sn, size, mtime = parts[0], parts[1], parts[2], parts[3]
        local_total += 1
        local_sns.add(sn)
        path_by_sn[sn] = (full, int(size), mtime)

# Diff
missing_on_server = sorted(sn for sn in local_sns if sn not in server)
missing_ci_only = sorted(sn for sn in local_sns if sn not in server and sn.lower() in server_ci)
already_present = sorted(sn for sn in local_sns if sn in server)

print(f"Local total: {local_total}")
print(f"Local unique serials: {len(local_sns)}")
print(f"Server total: {len(server)}")
print(f"")
print(f"Already on server (case-sensitive exact match): {len(already_present)}")
print(f"Missing on server (case-sensitive):             {len(missing_on_server)}")
print(f"    ...of which only differ by case:             {len(missing_ci_only)}")
print(f"")

# Write delta list (paths) to upload
with open(DELTA_OUT, "w") as f:
    for sn in missing_on_server:
        full, size, mtime = path_by_sn[sn]
        f.write(f"{sn}|{full}|{size}|{mtime}\n")

print(f"Wrote delta list ({len(missing_on_server)} entries) -> {DELTA_OUT}")

# Show sample of delta
if missing_on_server:
    print("\nFirst 10 missing SNs:")
    for sn in missing_on_server[:10]:
        full, size, mtime = path_by_sn[sn]
        print(f"  {sn}  ({size} bytes, {mtime[:19]})")
    print("\nLast 10 missing SNs:")
    for sn in missing_on_server[-10:]:
        full, size, mtime = path_by_sn[sn]
        print(f"  {sn}  ({size} bytes, {mtime[:19]})")

# Show counts by year-month for the delta
from collections import Counter
by_month = Counter()
for sn in missing_on_server:
    _, _, mtime = path_by_sn[sn]
    by_month[mtime[:7]] += 1
print("\nDelta by year-month:")
for k in sorted(by_month):
    print(f"  {k}: {by_month[k]}")
