"""
Load weekly time utilisation data from branch-specific CSV files.
"""
import csv
from pathlib import Path
from typing import Dict, List

def load_time_utilisation_by_branch() -> Dict[str, List[dict]]:
    """Load weekly time utilisation from branch-specific CSVs.
    Returns { branchName: [{ week, job_hours, quoting_hours, non_job_hours }, ...] }."""
    data_dir = Path(__file__).resolve().parent.parent.parent.parent / "data"
    branch_files = {
        "Bunbury": "time-util-bunbury.csv",
        "Busselton": "time-util-busselton.csv",
        "Mandurah": "time-util-mandurah.csv",
    }
    result = {}
    for branch_name, filename in branch_files.items():
        csv_path = data_dir / filename
        rows = []
        try:
            if csv_path.exists():
                with open(csv_path, encoding="utf-8") as f:
                    reader = csv.DictReader(f)
                    for row in reader:
                        week_str = (row.get("Week") or "").strip()
                        if not week_str:
                            continue
                        try:
                            job_hours = float(row.get("Job Hours", 0) or 0)
                            quoting_hours = float(row.get("Quoting Hours", 0) or 0)
                            non_job_hours = float(row.get("Non-Job Hours", 0) or 0)
                        except (ValueError, TypeError):
                            continue
                        rows.append({
                            "week": week_str,
                            "job_hours": round(job_hours, 2),
                            "quoting_hours": round(quoting_hours, 2),
                            "non_job_hours": round(non_job_hours, 2),
                        })
        except Exception:
            pass
        result[branch_name] = rows if rows else []
    return result


def load_time_utilisation_for_branch(branch_name: str) -> List[dict]:
    """Load time utilisation for a single branch. Returns empty list if branch unknown or no data."""
    all_data = load_time_utilisation_by_branch()
    return all_data.get(branch_name, [])
