#!/usr/bin/env python3
"""
Check function call logs for auto-loading performance metrics.

Searches recent function calls for "Total instances loaded" and prints
full logs for any calls where that number exceeds the threshold.

Usage:
    cd scripts
    python check_autoload_metrics.py
    python check_autoload_metrics.py --threshold 500 --limit 50
    python check_autoload_metrics.py --function validate-instances-shacl
"""

import argparse
import re
import sys
from pathlib import Path

import cognite_data_quality


DEFAULT_THRESHOLD = 200
DEFAULT_LIMIT = 25
DEFAULT_FUNCTION_ID = "data-quality-validation"
TOML_PATH = Path(__file__).parent.parent / "config/environments/abp-dev/abp-dev.toml"

METRIC_PATTERN = re.compile(r"Total instances loaded:\s*(\d+)", re.IGNORECASE)


def parse_args():
    parser = argparse.ArgumentParser(description="Check function call logs for auto-load metrics")
    parser.add_argument(
        "--function",
        default=DEFAULT_FUNCTION_ID,
        help=f"Function external ID (default: {DEFAULT_FUNCTION_ID})",
    )
    parser.add_argument(
        "--threshold",
        type=int,
        default=DEFAULT_THRESHOLD,
        help=f"Report calls where instances loaded > this value (default: {DEFAULT_THRESHOLD})",
    )
    parser.add_argument(
        "--limit",
        type=int,
        default=DEFAULT_LIMIT,
        help=f"Number of recent calls to inspect (default: {DEFAULT_LIMIT})",
    )
    return parser.parse_args()


def main():
    args = parse_args()
    client = cognite_data_quality.load_cognite_client_from_toml(str(TOML_PATH))

    print(f"Fetching last {args.limit} calls for function: {args.function}")
    print(f"Threshold: instances loaded > {args.threshold}\n")

    try:
        calls = client.functions.calls.list(
            function_external_id=args.function,
            limit=args.limit,
        )
    except Exception as e:
        print(f"ERROR fetching function calls: {e}")
        sys.exit(1)

    if not calls:
        print("No function calls found.")
        return

    print(f"Inspecting {len(calls)} call(s)...\n")

    hits = []

    for call in calls:
        try:
            logs = client.functions.calls.get_logs(
                call_id=call.id,
                function_external_id=args.function,
            )
        except Exception as e:
            print(f"  [call {call.id}] Could not fetch logs: {e}")
            continue

        log_text = "\n".join(entry.message for entry in (logs or []) if entry.message)
        match = METRIC_PATTERN.search(log_text)

        if match:
            count = int(match.group(1))
            status = call.status or "unknown"
            start = call.start_time or "?"
            print(f"  call {call.id} | status={status} | started={start} | instances_loaded={count}")
            if count > args.threshold:
                hits.append((call, log_text, count))
        else:
            # Metric line not present in this call's logs
            pass

    if not hits:
        print(f"\nNo calls found with instances loaded > {args.threshold}.")
        return

    print(f"\n{'='*70}")
    print(f"Found {len(hits)} call(s) exceeding threshold ({args.threshold}):")
    print(f"{'='*70}\n")

    for call, log_text, count in hits:
        print(f"### Call ID: {call.id}")
        print(f"    Status   : {call.status}")
        print(f"    Started  : {call.start_time}")
        print(f"    Ended    : {call.end_time}")
        print(f"    Instances: {count}")
        print(f"\n--- FULL LOG ---\n")
        print(log_text)
        print(f"\n{'='*70}\n")


if __name__ == "__main__":
    main()
