import json
import os
import re
import ast
from bank_validation_checks import (
    get_banking_month_count,
    get_name_match_score,
    get_recent_bounce_count,
    get_speculative_spend_percentage,
    calculate_abb_eligible_amount
)

def loose_json_load(file_path):
    """
    Attempts to parse JSON files that may have syntax errors.
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read().strip()

    try:
        return json.loads(content)
    except json.JSONDecodeError:
        pass 

    try:
        clean_content = re.sub(r',\s*([\]}])', r'\1', content)
        return json.loads(clean_content)
    except json.JSONDecodeError:
        pass

    try:
        return ast.literal_eval(content)
    except (ValueError, SyntaxError):
        pass

    try:
        replacements = {'null': 'None', 'true': 'True', 'false': 'False'}
        def replace_keywords(match):
            return replacements.get(match.group(0), match.group(0))
        
        hybrid_content = re.sub(r'\b(null|true|false)\b', replace_keywords, content)
        return ast.literal_eval(hybrid_content)
    except (ValueError, SyntaxError):
        pass

    raise ValueError("Failed to decode JSON with all loose parsing strategies.")

def main():
    file_path = 'tests/pirimid_analysis_json019beeb7-d2c4-5397-7781-5272daa22cbc.json'
    
    # 1. Load the JSON Data
    if not os.path.exists(file_path):
        print(f"Error: {file_path} not found.")
        return

    try:
        data = loose_json_load(file_path)
        print("Success: JSON decoded successfully.\n")
    except Exception as e:
        print(f"Critical Error: Could not read file. {e}")
        return

    # 2. Extract ONLY the 'analytics' key
    # In production, S3 returns the full file, and config accessor points to 'analytics'.
    analytics_data = data.get("analytics")

    # Safety check: If 'analytics' key isn't found, maybe the file IS the analytics object?
    if not analytics_data:
        print("Notice: 'analytics' key not found at root. Assuming root object is the analytics data.")
        analytics_data = data

    print("--- Bank Validation Checks Results ---\n")

    # ---------------------------------------------------------
    # 1. Test: get_banking_month_count
    # Input: analytics_data (dict)
    # Internal: Extracts 'accountProfiles'
    # ---------------------------------------------------------
    try:
        month_count = get_banking_month_count(analytics_data)
        print(f"1. Banking Month Count: {month_count}")
    except Exception as e:
        print(f"1. Banking Month Count: Failed - {e}")

    # ---------------------------------------------------------
    # 2. Test: get_name_match_score
    # Input: analytics_data (dict), Applicant Name
    # Internal: Extracts 'accountProfiles'
    # ---------------------------------------------------------
    dummy_applicant_name = "DHARMENDRA TIWARI" 
    try:
        match_score = get_name_match_score(analytics_data, dummy_applicant_name)
        print(f"2. Name Match Score (vs '{dummy_applicant_name}'): {match_score}")
    except Exception as e:
        print(f"2. Name Match Score: Failed - {e}")

    # ---------------------------------------------------------
    # 3. Test: get_recent_bounce_count
    # Input: analytics_data (dict), Lookback months
    # Internal: Extracts 'bounceAnalysis' -> 'accountWiseBounceAnalytics'
    # ---------------------------------------------------------
    dummy_lookback = 6 
    try:
        bounce_count = get_recent_bounce_count(analytics_data, dummy_lookback)
        print(f"3. Recent Bounce Count (Last {dummy_lookback} months): {bounce_count}")
    except Exception as e:
        print(f"3. Recent Bounce Count: Failed - {e}")

    # ---------------------------------------------------------
    # 4. Test: get_speculative_spend_percentage
    # Input: analytics_data (dict), Monthly Income
    # Internal: Extracts 'accountProfiles' AND 'allTransactions'
    # ---------------------------------------------------------
    dummy_income = 50000.0 
    try:
        spec_spend_pct = get_speculative_spend_percentage(analytics_data, dummy_income)
        print(f"4. Speculative Spend % (Income {dummy_income}): {spec_spend_pct}%")
    except Exception as e:
        print(f"4. Speculative Spend %: Failed - {e}")

    # ---------------------------------------------------------
    # 5. Test: calculate_abb_eligible_amount
    # Input: analytics_data (dict), Multiplier
    # Internal: Traverses 'overallAnalysis' -> 'customAbbs' -> ...
    # ---------------------------------------------------------
    dummy_multiplier = 0.5
    try:
        eligible_amount = calculate_abb_eligible_amount(analytics_data, dummy_multiplier)
        print(f"5. ABB Eligible Amount (Mult: {dummy_multiplier}): {eligible_amount}")
    except Exception as e:
        print(f"5. ABB Eligible Amount: Failed - {e}")

if __name__ == "__main__":
    main()