from __future__ import annotations

from datetime import datetime
from pathlib import Path
import re
from PySide6.QtCore import QUrl
from PySide6.QtGui import QDesktopServices
from mi100.paths import get_app_root
from mi100.services.pdf_documents import sanitize_filename_part

MONTHS_UA = {
    1: "01 Січень", 2: "02 Лютий", 3: "03 Березень", 4: "04 Квітень",
    5: "05 Травень", 6: "06 Червень", 7: "07 Липень", 8: "08 Серпень",
    9: "09 Вересень", 10: "10 Жовтень", 11: "11 Листопад", 12: "12 Грудень",
}


def _safe_name(text: str, fallback: str) -> str:
    cleaned = sanitize_filename_part((text or '').strip())
    cleaned = re.sub(r'\s+', ' ', cleaned).strip(' .')
    return cleaned or fallback


def project_root_dir() -> Path:
    root = get_app_root() / 'Projects'
    root.mkdir(parents=True, exist_ok=True)
    return root


def build_project_folder_path(*, project_title: str, company_name: str, created_date: str, stamp: datetime | None = None) -> Path:
    try:
        year, month, _ = [int(x) for x in str(created_date).split('-')[:3]]
    except Exception:
        now = datetime.now()
        year, month = now.year, now.month
    stamp = stamp or datetime.now()
    year_dir = str(year)
    month_dir = MONTHS_UA.get(month, f"{month:02d}")
    company_dir = _safe_name(company_name, 'Без назви замовника')
    title_dir = _safe_name(project_title, 'Без назви проєкту')
    leaf = f"{title_dir} ({stamp.strftime('%d.%m.%Y - %H-%M-%S')})"
    return project_root_dir() / year_dir / month_dir / company_dir / leaf


def ensure_project_folder(*, project_title: str, company_name: str, created_date: str, existing_path: str = '') -> str:
    existing = Path(existing_path) if existing_path else None
    if existing and existing.exists():
        return str(existing)
    path = build_project_folder_path(project_title=project_title, company_name=company_name, created_date=created_date)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.mkdir(parents=True, exist_ok=True)
    return str(path)


def open_folder(path: str) -> bool:
    p = Path(path)
    if not p.exists():
        return False
    return bool(QDesktopServices.openUrl(QUrl.fromLocalFile(str(p))))
