import asyncio
import time
import requests
import pandas as pd


def loop_io_requests(urls):
    results = []
    for url in urls:
        r = requests.get(url)
        if r.status_code == 200:
            results.append(r.text)
    return results


def loop_io_file(paths):
    contents = []
    for path in paths:
        with open(path, "r", encoding="utf-8") as f:
            contents.append(f.read())
    return contents


def loop_object_recreation(patterns, items):
    import re
    total = 0
    for item in items:
        for p in patterns:
            regex = re.compile(p)
            if regex.search(item):
                total += 1
    return total


def nested_loops_large_collection(data):
    count = 0
    for a in data:
        for b in data:
            for c in data:
                if a != b and b != c:
                    count += 1
    return count


def pandas_rowwise_iterrows(df: pd.DataFrame):
    values = []
    for _, row in df.iterrows():
        s = 0
        for col in df.columns:
            if isinstance(row[col], (int, float)):
                s += row[col]
        values.append(s)
    return values


def pandas_rowwise_apply(df: pd.DataFrame):
    def calc(row):
        s = 0
        for col in df.columns:
            if isinstance(row[col], (int, float)):
                s += row[col]
        return s

    return df.apply(calc, axis=1)


async def async_with_blocking_io(urls):
    texts = []
    for url in urls:
        r = requests.get(url)
        if r.status_code == 200:
            texts.append(r.text)
        time.sleep(0.1)
    return texts


async def async_mixed_operations(urls, paths):
    results = []
    for url in urls:
        r = requests.get(url)
        results.append(r.status_code)
    for path in paths:
        with open(path, "rb") as f:
            _ = f.read()
    time.sleep(0.05)
    return results


def large_collection_loop(items):
    total = 0
    for item in items:
        if isinstance(item, list) and len(item) > 10000:
            for x in item:
                total += int(bool(x))
    return total


def recursive_call(n):
    if n <= 0:
        return 0
    return 1 + recursive_call(n - 1)


def combined_bottlenecks(df: pd.DataFrame, urls, patterns):
    import re
    values = []
    for url in urls:
        r = requests.get(url)
        if r.status_code != 200:
            continue
        text = r.text
        for _, row in df.iterrows():
            for p in patterns:
                regex = re.compile(p)
                if regex.search(text):
                    values.append(row.to_dict())
    return values
