import os
import httpx
import io
import zipfile

NETLIFY_AUTH_TOKEN = os.environ.get("NETLIFY_AUTH_TOKEN", "")

# Load from secrets if not in environment
if not NETLIFY_AUTH_TOKEN:
    try:
        from pathlib import Path
        BASE_DIR = Path(__file__).parent.parent
        with open(BASE_DIR / "config" / "secrets.env", "r") as f:
            for line in f:
                if line.startswith("NETLIFY_AUTH_TOKEN="):
                    NETLIFY_AUTH_TOKEN = line.split("=", 1)[1].strip().strip('"\'')
    except Exception:
        pass

async def deploy_to_netlify(html_content: str, project_name: str) -> str:
    """
    Deploys a raw HTML string directly to Netlify using their REST API via a Zip payload.
    Creates a new site if one with the given name doesn't exist, or updates it if it does.
    Returns the deployment URL.
    """
    if not NETLIFY_AUTH_TOKEN:
        print("[Netlify Deploy] NETLIFY_AUTH_TOKEN not found. Skipping live deployment. (Hint: Add NETLIFY_AUTH_TOKEN to your .env)")
        return "deploy-skipped-no-token.netlify.app"
        
    headers = {
        "Authorization": f"Bearer {NETLIFY_AUTH_TOKEN}",
        "Content-Type": "application/zip"
    }
    
    # 1. Create a zip archive in memory containing index.html
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
        zip_file.writestr("index.html", html_content)
    zip_buffer.seek(0)
    
    async with httpx.AsyncClient() as client:
        # First, we need to check if the site exists, or just POST to create a new one.
        # Since we want a specific subdomain format, we create the site with that name.
        site_name = project_name
        
        # 2. Upload the zip directly to create a new site
        print(f"[{project_name}] Uploading Zip payload to Netlify Edge...")
        
        # This endpoint creates a new site AND deploys the zip
        deploy_response = await client.post(
            f"https://api.netlify.com/api/v1/sites",
            headers=headers,
            content=zip_buffer.read()
        )
        
        if deploy_response.status_code not in (200, 201):
            print(f"[Netlify Deploy] Site creation/upload failed: {deploy_response.text}")
            return "deployment-failed.netlify.app"
            
        data = deploy_response.json()
        site_id = data.get("id")
        deploy_url = data.get("url", "url-not-found.netlify.app")
        default_name = data.get("name")
        
        print(f"[{project_name}] \u26a1 LIVE at default domain: {deploy_url}")
        
        # 3. Rename the site to our project name if possible
        if site_id:
            try:
                print(f"[{project_name}] Attempting to rename site to {site_name}...")
                update_response = await client.patch(
                    f"https://api.netlify.com/api/v1/sites/{site_id}",
                    headers={"Authorization": f"Bearer {NETLIFY_AUTH_TOKEN}", "Content-Type": "application/json"},
                    json={"name": site_name}
                )
                if update_response.status_code in (200, 201):
                    new_url = update_response.json().get("url")
                    print(f"[{project_name}] \u2728 Renamed successfully: {new_url}")
                    return new_url
                else:
                    print(f"[{project_name}] Rename failed (name might be taken). Keeping default name: {default_name}")
            except Exception as e:
                print(f"[{project_name}] Error renaming site: {e}")
                
        return deploy_url
