"""Crawl the site with URL https://sportta.skatesweden.se/?fromDate=2025-09-01&toDate=2026-08-31&page=1
go to every event, extract data, and save to HTML file with the table.
"""

import datetime
import requests
from bs4 import BeautifulSoup
from models import CompetitionReport, save_reports


def swedish_dates_to_numeric(date_str):
    # Convert 13 september 2025 to 2025-09-13
    months = {
        "januari": "01",
        "februari": "02",
        "mars": "03",
        "april": "04",
        "maj": "05",
        "juni": "06",
        "juli": "07",
        "augusti": "08",
        "september": "09",
        "oktober": "10",
        "november": "11",
        "december": "12",
    }

    for month, month_num in months.items():
        if month in date_str:
            day, year = date_str.split(" ")[0], date_str.split(" ")[2]
            return f"{year}-{month_num}-{day.zfill(2)}"
    return "?"


def two_dates_to_start_end(date_str):
    # Convert "6 september 2025 - 7 september 2025" to ("2025-09-06", "2025-09-07")
    if " - " in date_str:
        start_str, end_str = date_str.split(" - ")
        start_date = swedish_dates_to_numeric(start_str)
        end_date = swedish_dates_to_numeric(end_str)
        return f"{start_date} - {end_date}"
    else:
        single_date = swedish_dates_to_numeric(date_str)
        return f"{single_date} - {single_date}"


def convert_second_date_to_week_number(date_str):
    two_dates = two_dates_to_start_end(date_str)
    # Convert "2025-09-20 - 2025-09-21" to "v38"
    _, end_date = two_dates.split(" - ")
    end_date_obj = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    week_number = end_date_obj.isocalendar()[1]
    return f"v{week_number}"


def build_schedule():
    table = []
    result_report = []
    pages_range = range(1, 32)  # Adjust the range as needed
    base_url = (
        "https://sportta.skatesweden.se/?fromDate=2025-09-01&toDate=2026-08-31&page="
    )
    for page in pages_range:
        url = f"{base_url}{page}"
        print(f"Processing page: {url}")
        response = requests.get(url, timeout=10)
        if response.status_code != 200:
            print(f"Failed to retrieve page {page}")
            continue
        soup = BeautifulSoup(response.content, "html.parser")
        event_links = soup.find_all("a", href=True)
        event_ids = [
            link["href"].split("/")[3].split("?")[0]
            for link in event_links
            if link.get_text(strip=True) == "Till detaljvy"
        ]

        for event_id in event_ids:
            event_url = f"https://sportta.skatesweden.se/sv/events/{event_id}?query=fromDate%3D2025-09-01%26toDate%3D2026-08-31%26page%3D{page}"
            print(f"Processing event: {event_url}")
            event_response = requests.get(event_url)
            if event_response.status_code != 200:
                print(f"Failed to retrieve event {event_id}")
                continue
            event_soup = BeautifulSoup(event_response.content, "html.parser")
            all_divs = event_soup.find_all("div")
            for div in all_divs:
                if div.find("dt") and "Namn på aktivitet" in div.find("dt").text:
                    event_name = div.find("dd").text.strip()
                if div.find("dt") and "Datum" in div.find("dt").text:
                    event_date = div.find("dd").text.strip()
                if div.find("dt") and "Plats" in div.find("dt").text:
                    event_location = div.find("dd").text.strip()
                if div.find("dt") and "Arrangör" in div.find("dt").text:
                    event_organizer = div.find("dd").text.strip()

            # Check if there is this link <a class="border-b-2 border-b-transparent pb-2 text-lg opacity-80 transition-all ease-in-out hover:border-b-primary/60 hover:opacity-100 focus:border-b-primary/60 focus:opacity-100" href="/sv/events/48ff1784-7f8e-481b-57fb-08dddf3c6652/entries">Anmälningar</a>
            # and if it is found, the load the page.
            all_a_hrefs = event_soup.find_all("a")
            for a_href in all_a_hrefs:
                if a_href.text.strip() == "Anmälningar":

                    anm_url = a_href["href"]
                    print("anm_url =", anm_url)
                    anm_url = f"https://sportta.skatesweden.se/{anm_url}"
                    # anm_url = "https://sportta.skatesweden.se/events/26792f67-d072-4ba7-57da-08dddf3c6652/entries"
                    # anm_url = "https://sportta.skatesweden.se/events/380e46b3-f0c8-4652-884c-08ddf5ba0e76/entries"

                    anm_response = requests.get(anm_url)
                    if anm_response.status_code != 200:
                        print(f"Failed to retrieve entries {event_id}")
                        continue
                    applied = dict()
                    anm_soup = BeautifulSoup(anm_response.content, "html.parser")
                    all_divs = anm_soup.find_all("div")
                    class_name = "NONE"
                    disc_name = "NONE"
                    for div in all_divs:

                        # <div class="border-b bg-gradient-to-r from-transparent to-muted p-4"><h3 class="scroll-m-20 tracking-tight text-xl font-semibold sm:text-2xl">Skåneserien Pool 1 Deltävling 1 - Skåneserien (Gul)</h3></div>
                        if div.find("h3"):

                            competition_name = div.find("h3").text.strip()
                            applied[competition_name] = 0
                            print("competition_name=", competition_name)

                        ps = div.find_all("p")
                        for p in ps:

                            # <p class="font-bold">Ungdom 16 Flickor</p>
                            # <p class="text-sm text-muted-foreground">Singelåkning</p>
                            # print("p=",p)
                            if p.get("class") == ["font-bold"]:
                                class_name = p.text.strip()
                            if p.get("class") == ["text-sm", "text-muted-foreground"]:
                                disc_name = p.text.strip()
                                # print("class=",class_name)
                        if div.get("aria-label") == "Antal anmälningar":
                            antal = div.text.strip()
                            print(class_name, antal)
                            if class_name == "Tränare" or class_name == "Lagledare":
                                pass
                            else:
                                print(class_name, disc_name, antal)
                                applied[competition_name] = applied.get(
                                    competition_name, 0
                                ) + int(antal)
                    # <div aria-label="Antal anmälningar" class="flex items-center font-bold"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2 h-4 w-4"><path d="m3 17 2 2 4-4"></path><path d="m3 7 2 2 4-4"></path><path d="M13 6h8"></path><path d="M13 12h8"></path><path d="M13 18h8"></path></svg><span>21</span></div>

            # print(applied)

            all_li = event_soup.find_all("li")
            for one_li in all_li:
                if one_li.find(
                    "header",
                    class_="rounded-t-md border bg-gradient-to-r from-transparent to-muted pt-4",
                ) and one_li.find("h3"):
                    h3 = one_li.find("h3")
                    competition_name = h3.text.strip()
                    # Now can we fill row about this competition!
                else:
                    continue
                li_div = one_li.find_all("div")

                competition_type = "?"
                li_p = one_li.find_all("p")
                for one_p in li_p:
                    print(one_p["class"])
                    if "font-semibold" in one_p["class"]:
                        competition_type = one_p.text.strip()

                competition_status = "?"
                for div in li_div:
                    if "rounded-full" in div["class"]:
                        competition_status = div.text.strip()
                competition_page = "?"
                for a in one_li.find_all("a"):
                    if "skate.webbplatsen.net" in a["href"]:
                        competition_page = a["href"]
                competition_combined_name = (
                    event_name
                    if event_name == competition_name
                    else f"{event_name} - {competition_name}"
                )

                divs = one_li.find_all("div")
                registration_period = "?"
                for div in divs:
                    if div.find("span") and "Anmälningsperiod" in div.find("span").text:
                        if div.find("time"):
                            registration_period = div.find("time").text.strip()
                week = convert_second_date_to_week_number(event_date)
                table.append(
                    [
                        week,
                        two_dates_to_start_end(event_date),
                        event_organizer,
                        event_location,
                        f'<a href="{event_url}">{competition_combined_name}</a>',
                        event_name,
                        competition_name,
                        competition_type,
                        competition_status,
                        two_dates_to_start_end(registration_period),
                        f'<a href="{competition_page}">Resultat</a>',
                        applied.get(competition_name, "NONE"),
                    ]
                )
                competition_id = (
                    competition_page.split("/")[-2] if competition_page != "?" else "?"
                )
                report = CompetitionReport(
                    week=week,
                    competition_combined_name=competition_combined_name,
                    competition_type=competition_type,
                    competition_page=competition_page,
                    competition_id=competition_id,
                    competition_status=competition_status,
                )
                result_report.append(report)

                applied[competition_name] = 0

            # print("tanle=",table)

    return table, result_report


def split_table_by_competition_type(table):
    types = {}
    for row in table:
        comp_type = row[7]
        if comp_type not in types:
            types[comp_type] = []
        types[comp_type].append(row)
    return types


headers = [
    "V.",
    "Datum",
    "Arrangör",
    "Ishall",
    "Event/Tävling",
    "Event",
    "Tävling",
    "Tävlingstyp",
    "Status",
    "Anmälningsperiod",
    "Resultat",
    "Anmälningar",
]


def save_to_Excel(table, f):
    import xlsxwriter

    workbook = xlsxwriter.Workbook(f)
    worksheet = workbook.add_worksheet()

    # Write headers
    for col_num, header in enumerate(headers):
        worksheet.write(0, col_num, header)

    # Write data
    for row_num, row in enumerate(table, start=1):
        for col_num, col in enumerate(row):
            # if "col" is a <a href=""...>text</a>, extract the text and crate a link in Excel
            if isinstance(col, str) and col.startswith('<a href="'):
                from bs4 import BeautifulSoup

                soup = BeautifulSoup(col, "html.parser")
                text = soup.get_text()
                href = soup.find("a")["href"]
                worksheet.write_url(row_num, col_num, href, string=text)
            else:
                worksheet.write(row_num, col_num, col)

    workbook.close()


def save_to_html(table, f):

    f.write('<div class="table-container">')
    f.write('<table class="responsive-table" border="1">')
    f.write(
        "<colgroup>"
        "<col />"
        "<col />"
        '<col class="col-fixed" />'  # 2nd column fixed width
        '<col class="col-fixed" />'  # 2nd column fixed width
        '<col class="col-fixed" />'  # 3rd column fixed width
        "<col />"
        "<col />"
        "<col />"
        "<col />"
        "<col />"
        "<col />"
        "<col />"
        "</colgroup>"
    )

    f.write("<thead><tr>")
    for header in headers:
        f.write(f"<th>{header}</th>")
    f.write("</tr></thead>\n")
    if False:
        f.write(
            """\n<tr>
                <th>V.</th>
                <th>Datum</th>
                <th>Arrangör</th> 
                <th>Ishall</th>
                <th>Event/Tävling</th>
                <th>Event</th>
                <th>Tävling</th>
                <th>Tävlingstyp</th>
                <th>Status</th>
                <th>Anmälningsperiod</th>
                <th>Resultat</th>
                <th>Anmälningar</th>
            </tr>\n
                """
        )
    for row in table:
        f.write("\n<tr>")
        for col in row:
            f.write(f"  <td>{col}</td>\n")
        f.write("</tr>\n")
    f.write("</table></div>\n\n")


def write_html_file(schedule_table, filename):
    with open(filename, "w", encoding="utf-8") as f:
        # HTML header (correct order for meta)
        f.write("<!doctype html>\n")
        f.write('<html lang="sv">\n')
        f.write("<head>\n")
        f.write('<meta charset="utf-8">\n')
        f.write(
            '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
        )
        f.write("<title>Swedish Figure Skating Competitions 2025-2026</title>\n")
        f.write(
            "<style>"
            ".table-container{overflow-x:auto;-webkit-overflow-scrolling:touch;}"
            ".responsive-table{table-layout:fixed;width:100%;border-collapse:collapse;}"
            ".responsive-table th,.responsive-table td{padding:6px 8px;font-size:14px;vertical-align:top;word-break:break-word;overflow-wrap:anywhere;}"
            ".responsive-table td a{word-break:break-all;}"
            # /* fixed 2nd and 3rd cols on desktop */
            ".col-fixed{width:200px;}"
            # /* keep all columns, but allow scroll and slightly smaller text on very small screens */
            "@media (max-width: 400px){"
            " .responsive-table{min-width:900px;}"  # /* force horizontal scroll */
            " .responsive-table th,.responsive-table td{padding:4px 6px;font-size:12px;}"
            " .col-fixed{width:160px;}"  # /* modest shrink, not hidden */
            "}"
            "</style>\n"
        )
        f.write("</head>\n<body>\n")

        f.write(
            f'<p>Skapades från <a href="https://sportta.skatesweden.se">SportTA</a> automatiskt klockan {datetime.datetime.now().isoformat()}</p>\n'
        )

        f.write("<h1>Tävlingar per tävlingstyp</h1>\n")

        typer_i_alphabetisk_ordning = sorted(
            split_table_by_competition_type(schedule_table).keys()
        )

        for comp_type in typer_i_alphabetisk_ordning:
            f.write(f'<a href="#{comp_type}">{comp_type}</a><br/>\n')
        f.write('<a href="#all">Alla tävlingar i tidsordning</a><br/>\n')
        f.write("<hr/>\n")

        for comp_type in typer_i_alphabetisk_ordning:
            f.write(f'<a name="{comp_type}"></a>\n')
            f.write(f"<h2>{comp_type}</h2>\n")

            save_to_html(
                split_table_by_competition_type(schedule_table).get(comp_type, []), f
            )

        f.write('<a name="all"></a>\n')
        f.write("<h1>Alla tävlingar i tidsordning</h1>\n")
        save_to_html(schedule_table, f)
        f.write("</body></html>\n")
        save_to_Excel(schedule_table, filename.replace(".html", ".xlsx"))


if __name__ == "__main__":
    schedule_table, result_report = build_schedule()
    filename = "schedule.html"
    write_html_file(schedule_table, filename)

    save_reports(result_report, "result_report.json")

    print(f"Schedule saved to {filename}")
