from __future__ import annotations

from pathlib import Path
import json
import re
from playwright.sync_api import Page

from .. import selector as settings_sel
from .....core.artifacts import shot
from .....core.log import log_step, pause


OUTPUT_PATH = Path(__file__).resolve().parents[6] / "zones" / "overheads" / "overheads.json"


def run(page: Page, cfg, run_dir: Path) -> list[dict]:
    settings_sel.ensure_settings_page(page)
    settings_sel.click_settings_group(page, key="timesheets", label="Timesheets")

    # Click Overheads inside Timesheets group
    group = page.locator("[data-aroflo-settingsgroup='timesheets']")
    link = group.locator("a.item-link", has_text="Overheads")
    if link.count() == 0:
        link = group.locator("[data-aroflo-settingssetting='Overheads'] a")
    link.first.click(timeout=5000, force=True)

    page.wait_for_function(
        "() => location.href.toLowerCase().includes('/ims/siteadmin/resource/allocation')",
        timeout=45_000,
    )

    shot(page, run_dir, "sa-timesheets-overheads-01")
    log_step("sa-timesheets-overheads-01", page)
    pause(cfg, "SiteAdmin: Settings > Timesheets > Overheads ready")

    overheads = list_overheads(page)
    try:
        OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
        OUTPUT_PATH.write_text(json.dumps(overheads, indent=2, ensure_ascii=True))
    except Exception:
        pass
    return overheads


def list_overheads(page: Page) -> list[dict]:
    rows = page.locator("table#tblAllocations tbody tr")
    results: list[dict] = []
    for i in range(rows.count()):
        row = rows.nth(i)
        name_input = row.locator("input[name^='Allocation']")
        if name_input.count() == 0:
            continue
        name = (name_input.first.get_attribute("value") or "").strip()
        name_attr = name_input.first.get_attribute("name") or ""
        m = re.search(r"Allocation(\\d+)", name_attr)
        alloc_id = m.group(1) if m else ""

        def _input_val(prefix: str) -> str:
            loc = row.locator(f"input[name^='{prefix}']")
            if loc.count() == 0:
                return ""
            return (loc.first.get_attribute("value") or "").strip()

        def _checkbox_val(prefix: str) -> bool:
            loc = row.locator(f"input[type='checkbox'][name^='{prefix}']")
            if loc.count() == 0:
                return False
            return loc.first.is_checked()

        type_sel = row.locator("select[name^='Class']")
        overhead_type = ""
        if type_sel.count():
            opt = type_sel.first.locator("option:checked")
            overhead_type = (opt.first.text_content() or "").strip()

        unit = _input_val("UnitType")
        cost_rate = _input_val("UnitRate")
        sell_rate = _input_val("UnitSellEx")

        if not unit:
            unit = (row.locator("td").nth(3).text_content() or "").strip()
        if not cost_rate:
            cost_rate = (row.locator("td").nth(4).text_content() or "").strip()
        if not sell_rate:
            sell_rate = (row.locator("td").nth(5).text_content() or "").strip()

        results.append(
            {
                "id": alloc_id,
                "name": name,
                "type": overhead_type,
                "unit": unit,
                "cost_rate": cost_rate,
                "sell_rate": sell_rate,
                "calendar_link": _checkbox_val("Calendar"),
                "include_in_timesheet_total": _checkbox_val("inctstot"),
                "task_overhead": _checkbox_val("taskoverhead"),
            }
        )

    return results
