#!/usr/bin/env python3
"""Round 2 — re-validate the operations that failed in wsp_validate.py."""
import os
import re
import sys
import time
from datetime import datetime, timedelta

sys.path.insert(0, os.path.dirname(__file__))
from wsp_validate import (
    setup_certs, cleanup_certs, make_session, soap_call, parse_response,
)


def t(session, op, fields, contract='ISupplierWebService'):
    try:
        r, elapsed = soap_call(session, op, fields, contract=contract)
        p = parse_response(r.text)
        desc = (p['description'] or '')[:120]
        print(f'  {op:<22} {p["status"]:<18} PageTotal={p["page_total"]} '
              f'size={p["size"]/1024:.0f}KB  {elapsed:.1f}s')
        if desc:
            print(f'    desc: {desc}')
        return p
    except Exception as e:
        print(f'  {op:<22} ERROR: {e}')
        return None


def main():
    setup_certs()
    s = make_session()
    today = datetime.now().date()
    week_ago = today - timedelta(days=7)
    fmt_s = lambda d: d.strftime('%Y-%m-%dT00:00:00')
    fmt_e = lambda d: d.strftime('%Y-%m-%dT23:59:59')

    print('=== Round 2: Beletage-scoped (Su*) with namespace fix ===')
    # SuContracts now uses .Contracts namespace (auto-applied via OP_NAMESPACE)
    t(s, 'SuContracts', {
        'ContractEndDate': fmt_e(today),
        'ContractStartDate': fmt_s(today - timedelta(days=365 * 5)),
        'PageIndex': 1,
    })

    # SuInvoices — short window first to learn the limit
    print('\n  SuInvoices: probing window-size limit')
    for win_days in [7, 30, 90, 365]:
        p = t(s, 'SuInvoices', {
            'MaxDate': fmt_e(today),
            'MinDate': fmt_s(today - timedelta(days=win_days)),
            'PageIndex': 1,
        })

    # SuDirectAcquisitions — try alternate field names too
    print('\n  SuDirectAcquisitions: try with PublicationStart/EndDate first')
    t(s, 'SuDirectAcquisitions', {
        'PageIndex': 1,
        'PublicationEndDate': fmt_e(today),
        'PublicationStartDate': fmt_s(week_ago),
    })

    # SU_EAProcedure — try common date field names
    print('\n  SU_EAProcedure: probe field names')
    for field_set_name, fields in [
        ('PublicationStart/End', {
            'PageIndex': 1,
            'PublicationEndDate': fmt_e(today),
            'PublicationStartDate': fmt_s(week_ago),
        }),
        ('Start/End', {
            'EndDate': fmt_e(today),
            'PageIndex': 1,
            'StartDate': fmt_s(week_ago),
        }),
        ('AuctionStart/End', {
            'AuctionEndDate': fmt_e(today),
            'AuctionStartDate': fmt_s(week_ago),
            'PageIndex': 1,
        }),
        ('Min/Max', {
            'MaxDate': fmt_e(today),
            'MinDate': fmt_s(week_ago),
            'PageIndex': 1,
        }),
    ]:
        print(f'  {field_set_name}:')
        t(s, 'SU_EAProcedure', fields)

    # Confirm SU_CaNotices day-by-day pagination is stable
    print('\n=== T6: 3 sequential days SU_CaNotices (per-day windows) ===')
    for d in range(3):
        day = today - timedelta(days=d + 1)
        p = t(s, 'SU_CaNotices', {
            'PageIndex': 1,
            'PublicationEndDate': fmt_e(day),
            'PublicationStartDate': fmt_s(day),
        })

    # Test page navigation: page 2 of yesterday's CaNotices
    print('\n=== T7: Page 2 navigation (yesterday) ===')
    yesterday = today - timedelta(days=1)
    for page in [1, 2, 5]:
        p = t(s, 'SU_CaNotices', {
            'PageIndex': page,
            'PublicationEndDate': fmt_e(yesterday),
            'PublicationStartDate': fmt_s(yesterday),
        })

    cleanup_certs()


if __name__ == '__main__':
    main()
