import os
import re
import httpx
import logging
import uuid
from pathlib import Path
from core.config import settings

logger = logging.getLogger(__name__)

def download_file_from_hub(relative_path: str) -> bool:
    """
    Downloads a file from the Hub to the local storage.
    relative_path: e.g., 'uploads/help/pdfs/myfile.pdf' or '/api/uploads/help/image.png'
    """
    if not settings.CENTRAL_SERVER_URL or settings.CENTRAL_SERVER_URL == '""':
        return False

    # Clean the path
    clean_path = relative_path.replace("/api/uploads/", "uploads/")
    if clean_path.startswith("/"):
        clean_path = clean_path[1:]
    
    # Check if it starts with uploads
    if not clean_path.startswith("uploads/"):
        # If it doesn't start with uploads, it might just be the filename or a subpath
        # We assume it's relative to /app/
        pass

    local_path = Path(clean_path)
    if local_path.exists():
        logger.info(f"File {clean_path} already exists, skipping download.")
        return True

    # Ensure directories exist
    local_path.parent.mkdir(parents=True, exist_ok=True)

    # Resolve Hub Base URL
    # CENTRAL_SERVER_URL is usually http://hub:8000/api/v1/core/help-center/sync/
    # We want http://hub:8000/api/
    base_url = settings.CENTRAL_SERVER_URL.split("/v1/")[0]
    # The file in backend is served usually under /api/uploads/...
    # But clean_path is just "uploads/...". So the Hub route is base_url + "/" + clean_path 
    hub_file_url = f"{base_url}/{clean_path}"

    logger.info(f"Downloading asset from Hub: {hub_file_url} -> {local_path}")
    
    try:
        with httpx.Client() as client:
            response = client.get(hub_file_url, timeout=30.0)
            if response.status_code == 200:
                with open(local_path, "wb") as f:
                    f.write(response.content)
                logger.info(f"Successfully downloaded {clean_path}")
                return True
            else:
                logger.warning(f"Failed to download {clean_path}: Status {response.status_code} URL: {hub_file_url}")
                return False
    except Exception as e:
        logger.error(f"Error downloading {clean_path}: {str(e)}")
        return False

def sync_assets_from_content(content: str):
    """
    Parses markdown content for image URLs and downloads them if they are local references.
    Example: ![alt text](/api/uploads/help/uuid.png)
    """
    if not content:
        return

    # Regex for markdown images: ![...](/api/uploads/...)
    image_pattern = r'!\[.*?\]\((/api/uploads/.*?)\)'
    matches = re.findall(image_pattern, content)
    
    for asset_url in matches:
        download_file_from_hub(asset_url)
