import re
from typing import Any, Dict, Optional

FOLDER_ID_RE = re.compile(r"/folders/([a-zA-Z0-9-_]+)")
QUERY_ID_RE = re.compile(r"[?&]id=([a-zA-Z0-9-_]+)")


def extract_folder_id(url: str | None) -> Optional[str]:
    if not url:
        return None
    match = FOLDER_ID_RE.search(url)
    if match:
        return match.group(1)
    match = QUERY_ID_RE.search(url)
    return match.group(1) if match else None


def extract_google_file_id(url: str) -> str | None:
    patterns = [
        r"/d/([a-zA-Z0-9_-]{10,})",  # /d/<id>/
        r"id=([a-zA-Z0-9_-]{10,})",  # ?id=<id>
        r"spreadsheets/d/([a-zA-Z0-9_-]{10,})",  # spreadsheets/d/<id>
        r"drive/folders/([a-zA-Z0-9_-]{10,})",  # folders/<id>
    ]

    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    return None


def duplicate_file_to_drive_folder(
    drive_service: Any,
    file_url: str,
    folder_url: str,
    prefix_file_name: str | None = None,
) -> Dict[str, Any]:
    """Duplicate a Google Drive file into a target folder.

    Args:
        drive_service: Google Drive API service instance.
        file_url: Full URL of the source Drive file to duplicate.
        folder_url: Full URL of the destination Drive folder.
        prefix_file_name: Optional string to prepend to the duplicated file's name.

    Returns:
        Dict with keys:
        - success: Boolean
        - id: The ID of the newly created file when successful, else None.
        - url: URL of the duplicated file or sheet when successful, else None.
        - error: Error code string on failure, otherwise None.
        - error_msg: Optional raw error message from the API when available.
    """
    file_id = extract_google_file_id(file_url)

    if not file_id:
        return {"success": False, "id": None, "url": None, "error": "Invalid file url"}

    folder_id = extract_folder_id(folder_url)
    if not folder_id:
        return {
            "success": False,
            "id": None,
            "url": None,
            "error": "missing_or_malformed_url",
        }

    try:
        src = (
            drive_service.files()
            .get(fileId=file_id, fields="id,name,mimeType")
            .execute()
        )

        name = src.get("name", "Copy")
        if prefix_file_name:
            name = f"{prefix_file_name}{name}"
        src_mime = src.get("mimeType", "")

        body = {"name": name, "parents": [folder_id]}
        dup = (
            drive_service.files()
            .copy(fileId=file_id, body=body, fields="id,webViewLink")
            .execute()
        )

        new_id = dup.get("id")

        if src_mime == "application/vnd.google-apps.spreadsheet":
            new_url = f"https://docs.google.com/spreadsheets/d/{new_id}/edit"
        else:
            new_url = (
                dup.get("webViewLink")
                or f"https://drive.google.com/file/d/{new_id}/view"
            )

        return {"success": True, "id": new_id, "url": new_url, "error": None}

    except Exception as e:
        msg = str(e)
        if "HttpError 403" in msg or "HttpError 404" in msg:
            return {
                "success": False,
                "id": None,
                "url": None,
                "error": "forbidden_or_not_found",
                "error_msg": msg,
            }
        return {
            "success": False,
            "id": None,
            "url": None,
            "error": f"request_exception:{e.__class__.__name__}",
            "error_msg": msg,
        }
