import re
from simple_salesforce import Salesforce

# Authenticate (or pass in separately if preferred)
sf = Salesforce(
    instance_url='https://sitetracker-tillmanfiber2--sitetracker.vf.force.com',
    session_id='00DDm000000L2eu!AQEAQObkypZDOwvBIMx9oTyIE6ZVvjYhrhyuuiMzmD6g3mO3ODzIRi0tlV54yX58r02WZ_wv1aj9y3XwU0hxVoYo7sIm3b4l'
)

def parse_distribution_prefix(cabinet_name):
    match = re.match(r"FX4-F([A-Z]{2})-(\d{2})", cabinet_name.upper())
    if match:
        letters = match.group(1)
        suffix_num = int(match.group(2))
        prefix = f"D-H{letters}"
        base = suffix_num * 100 + 1
        return prefix, base
    return "D-HXX", 1

def extract_suffix(wo):
    match = re.search(r'(\d+)$', wo)
    return int(match.group(1)) if match else -1

def get_next_distribution_wo(cabinet_name):
    match = re.match(r"FX4-F([A-Z]{2})-(\d{2})", cabinet_name.upper())
    if not match:
        return None, "Invalid cabinet format"

    letters = match.group(1)
    suffix = int(match.group(2))
    block = suffix  # 01 → 1, 02 → 2, etc.

    full_prefix = f"D-H{letters}{block}"

    # Query SiteTracker for ring number
    result = sf.query(f"""
        SELECT Id, Ring_Number__c 
        FROM sitetracker__Project__c 
        WHERE LLD_WO_Number__c = '{cabinet_name}'
        LIMIT 1
    """)

    if not result['records']:
        return None, None

    ring_number = result['records'][0]['Ring_Number__c']

    # Get all distribution WOs on that ring
    dist_result = sf.query_all(f"""
        SELECT LLD_WO_Number__c, County__c, MO__c, Distribution_Area__c,
               Engineering_Vendor_Assigned_Name__c, Construction_Vendor_Assigned_Name__c
        FROM sitetracker__Project__c 
        WHERE Ring_Number__c = '{ring_number}'
        AND Job_Type__c = 'Distribution'
    """)

    wo_records = dist_result['records']

    # Filter only WOs with correct full prefix like D-HNS1
    matching_wos = [r for r in wo_records if r["LLD_WO_Number__c"].startswith(full_prefix)]

    def extract_suffix(wo_name):
        match = re.match(fr"{full_prefix}(\d+)", wo_name)
        return int(match.group(1)) if match else -1

    if not matching_wos:
        next_suffix = 1
    else:
        highest = max(matching_wos, key=lambda r: extract_suffix(r["LLD_WO_Number__c"]))
        last_suffix = extract_suffix(highest["LLD_WO_Number__c"])
        next_suffix = last_suffix + 1

    next_wo = f"{full_prefix}{next_suffix:02d}"
    # print("Full Prefix: ", full_prefix)
    # print("Next Suffix: ", next_suffix)
    # print("Next WO: ", next_wo)

    # Pull metadata from the highest matching WO
    metadata_source = matching_wos[-1] if matching_wos else wo_records[0]
    return next_wo, {
        "MO": metadata_source.get("MO__c", "N/A"),
        "County": metadata_source.get("County__c", "N/A"),
        "Distribution_Area": metadata_source.get("Distribution_Area__c", "N/A"),
        "Engineering_Vendor": metadata_source.get("Engineering_Vendor_Assigned_Name__c", "N/A"),
        "Construction_Vendor": metadata_source.get("Construction_Vendor_Assigned_Name__c", "N/A")
    }

