import requests
from bs4 import BeautifulSoup
import re
import time

def get_military_data(channel_username, depth=5):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
    last_id = None
    
    for i in range(depth):
        url = f"https://t.me/s/{channel_username}"
        if last_id:
            url += f"?before={last_id}"
            
        try:
            response = requests.get(url, headers=headers, timeout=10)
            soup = BeautifulSoup(response.text, 'html.parser')
            messages = soup.find_all('div', class_='tgme_widget_message')

            if not messages:
                break

            first_msg_data = messages[0].get('data-post')
            if first_msg_data:
                last_id = first_msg_data.split('/')[-1]

            for msg in reversed(messages):
                text_elem = msg.find('div', class_='tgme_widget_message_text')
                if not text_elem:
                    continue
                    
                text = " ".join(text_elem.get_text(separator=' ').split())
                text_lower = text.lower()

                if "темп" in text_lower and "продвижения" in text_lower:
                    # Улучшенная регулярка для дат (ловит и "с 14 по 17", и "с 14 февраля по 17 февраля")
                    dates_match = re.search(r"с (.*?)(?=\.|\s+темп)", text_lower)
                    # Твои регулярки для цифр — отличные
                    pace_match = re.search(r"темп[^+-]*([+-]\d+[.,]\d+)", text_lower)
                    total_match = re.search(r"общее продвижение\s*(\d+[.,]\d+)", text_lower)
                    
                    if pace_match:
                        return {
                            "status": "success",
                            "dates": dates_match.group(1).strip() if dates_match else "не указаны",
                            "pace": pace_match.group(1).replace(',', '.'),
                            "total": total_match.group(1).replace(',', '.') if total_match else "0",
                            "post_id": msg.get('data-post').split('/')[-1]
                        }
            time.sleep(1)
        except Exception as e:
            print(f"Ошибка на итерации {i}: {e}")
            continue

    return {"status": "error", "message": "Сводка не найдена в последних постах"}