from bs4 import BeautifulSoup

import re

from .. import models

async def bugs_parser(html: str, url: str):
    soup = BeautifulSoup(html, "html.parser")
    pre_tag = soup.find("pre")
    if not pre_tag:
        return {}
    text = pre_tag.get_text()

    lines = text.strip().splitlines()
    data = {}
    section_name = None
    bug_pattern = re.compile(r"#(\d+)\s+([^\t]+)\s+([^\t]+)\s+([^\t]+)")
    description_buffer = ""
    current_bug = None

    for line in lines:
        header_match = re.match(
            r"^\s*(\d+)\s+(NEW|RESOLVED|REOPENED|RANDOM|OLD)\s+bugs?.*", line)
        if header_match:
            if current_bug and section_name:
                current_bug["summary"] = description_buffer.strip()
                data.setdefault(section_name, []).append(current_bug)
                current_bug = None
                description_buffer = ""

            section_name = _get_bug_section_name(line)
            continue

        bug_match = bug_pattern.match(line)
        if bug_match:
            if current_bug and section_name:
                current_bug["summary"] = description_buffer.strip()
                data.setdefault(section_name, []).append(current_bug)

            status = bug_match.group(4).strip()
            if status == "---":
                status = None

            current_bug = {
                "id": int(bug_match.group(1)),
                "component": bug_match.group(2).strip(),
                "priority": bug_match.group(3).strip(),
                "status": status
            }
            description_buffer = ""
        elif current_bug:
            if not line.strip():
                continue
            if re.match(r"^Total\s+\d+\s+pending bugs", line.strip(), re.IGNORECASE):
                break
            description_buffer += line.strip() + " "

    if current_bug and section_name:
        current_bug["summary"] = description_buffer.strip()
        data.setdefault(section_name, []).append(current_bug)
    
    data["url"] = url

    return models.BugsModel(**data)


def _get_bug_section_name(line: str) -> str:
    line = line.lower()
    if "new" in line and "resolved" in line:
        return "quickly_resolved"
    elif "new" in line:
        return "new"
    elif "old" in line:
        return "old"
    elif "resolved" in line:
        return "resolved"
    elif "reopened" in line:
        return "reopened"
    elif "random" in line:
        return "random"
