"""
Cleanup script to remove malformed accounting codes from the database.
These are hex-like codes like 402d, 61cd, 40ea70, etc. that were created
in error and should not exist in a proper chart of accounts.
"""
import requests
import sys

API_BASE = 'http://localhost:8010'

def get_malformed_codes():
    """Fetch all malformed accounting codes (codes containing hex letters a-f)."""
    r = requests.get(f'{API_BASE}/api/v1/general-ledger/chart-of-accounts', timeout=10)
    data = r.json()

    bad_codes = []

    def extract_bad_codes(items):
        for item in items:
            code = item.get('code', '')
            # Check for hex-like codes (contain letters a-f after digits)
            if code and any(c in code for c in 'abcdefABCDEF'):
                bad_codes.append({
                    'id': item.get('id'),
                    'code': code,
                    'name': item.get('name')
                })
            if item.get('children'):
                extract_bad_codes(item['children'])

    extract_bad_codes(data)
    return bad_codes

def delete_codes(codes):
    """Delete the malformed codes."""
    deleted = 0
    failed = 0

    for code in codes:
        try:
            # Use the accounting-codes endpoint for deletion
            resp = requests.delete(
                f"{API_BASE}/api/v1/accounting-codes/{code['id']}",
                timeout=10
            )
            if resp.status_code in [200, 204]:
                print(f"[OK] Deleted: {code['code']} - {code['name']}")
                deleted += 1
            else:
                error_detail = ""
                try:
                    error_detail = resp.json().get('detail', '')
                except:
                    pass
                print(f"[FAIL] {code['code']}: HTTP {resp.status_code} - {error_detail}")
                failed += 1
        except Exception as e:
            print(f"[ERR] {code['code']}: {e}")
            failed += 1

    return deleted, failed

def main():
    print("Scanning for malformed accounting codes...")
    bad_codes = get_malformed_codes()

    if not bad_codes:
        print("No malformed codes found. Database is clean!")
        return 0

    print(f"\nFound {len(bad_codes)} malformed accounting codes:")
    for c in bad_codes:
        print(f"  - {c['code']}: {c['name']}")

    print("\nDeleting malformed codes...")
    deleted, failed = delete_codes(bad_codes)

    print(f"\n{'='*50}")
    print(f"Summary: {deleted} deleted, {failed} failed")

    if failed > 0:
        return 1
    return 0

if __name__ == '__main__':
    sys.exit(main())
