from utils_v2.string import json
from scripts import common
from tcaoff.async_tcaoff import AsyncTheCAOffice
import asyncio
import datetime

# Explicitly mention the expected file paths for other devs to maintain:
print("PROJ. DIR.  :", common.PROJ_DIR)
print("COSEC CREDS :", common.COSEC_CREDS_FILE)
print("TCAOFF CREDS:", common.TCAOFF_CREDS_FILE)

# Read required credentials:
cosec_creds = json.from_file(common.COSEC_CREDS_FILE)
tcaoff_creds = json.from_file(common.TCAOFF_CREDS_FILE)

# Create the clients:
tcaoff_client = AsyncTheCAOffice(
    username = tcaoff_creds["creds"]["username"],
    password = tcaoff_creds["creds"]["password"],
    debug = True,
    debug_only_errors = False,
)

async def main():

    # Ensure login:
    if not await tcaoff_client.login():
        return

    # Get the data:
    raw_records = await tcaoff_client.attendance_register(
        target_month = datetime.datetime.now(),
        raise_exception = True
    )
    print(f"RAW RECORDS ({len(raw_records)}):", json.to_string(raw_records))

    # Format the data for preview:
    formatted_records = []
    for r in raw_records:
        cosec_data = json.from_string(r.get("json_notes", "{}")).get("cosec", {})
        if cosec_data:
            cosec_data.update({
                "cosecId": r["pseudonym"],
                "tcaoffId": r["user_id"],
            })
            formatted_records.append(cosec_data)

    # Show the formatted data for debugging:
    print(f"FORMATTED RECORDS ({len(formatted_records)}):", json.to_string(formatted_records[:10]))
    print(f"Found {len(formatted_records)} record(s).")

    # Log out:
    await tcaoff_client.logout()

asyncio.run(main())
