# SEO-Optimized News Bot with Summarization + Image + WordPress Posting
# Runs FREE in Google Colab

#@title Setup Environment
#!pip install transformers requests beautifulsoup4 python-dotenv Pillow

import streamlit as st
import os
import requests
import time
import base64
from bs4 import BeautifulSoup
from datetime import datetime
from PIL import Image
from io import BytesIO
import torch
from transformers import pipeline
from diffusers import StableDiffusionPipeline

from dotenv import load_dotenv
load_dotenv()
# Environment Variables (Replace with your info or use dotenv)

NEWS_API_KEY = os.getenv("FREE_NEWS_API_KEY")
WP_SITE_URL = os.getenv("WP_SITE_URL")
WP_USERNAME = os.getenv("WP_USER_EMAIL")
WP_APP_PASSWORD = os.getenv("WP_PASSWORD")
NEWS_CATEGORY_ID = os.getenv("NEWS_CATEGORY_ID")
# HUGGINGFACE_API_TOKEN = os.getenv("HF_API_TOKEN")
# Streamlit UI
st.set_page_config(page_title="AI Blog Post Generator", layout="centered")
st.title("AI Blog Post Generator")
st.markdown("Enter a blog title, and we'll help you generate a summarized and paraphrased blog post using AI.")

# Input box
search_title = st.text_input("Blog Title", placeholder="e.g. The Future of AI in Education")

# Models
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
paraphraser = pipeline("text2text-generation", model="tuner007/pegasus_paraphrase")
# Load the model to GPU
pipe = StableDiffusionPipeline.from_pretrained(
    "stabilityai/sd-turbo",
    torch_dtype=torch.float32
).to("cpu")

# 📰 STEP 1: Fetch Top AI News

def get_ai_news():
    print("-----------API Key-------------------")
    print(NEWS_API_KEY)

    query = (
        "artificial intelligence AND (jobs OR employment OR workforce OR automation OR layoffs OR hiring)"
    )

    url = (
            "https://newsapi.org/v2/everything?"
            f"q={requests.utils.quote(query)}"
            "&sortBy=publishedAt"
            "&language=en"
            "&pageSize=3"
            f"&apiKey={NEWS_API_KEY}"
        )
    
    res = requests.get(url)
    res.raise_for_status()
    return res.json().get("articles", [])

# 📄 STEP 2: Extract Clean Article Text

def extract_article_text(url):
    try:
        res = requests.get(url, timeout=10)
        soup = BeautifulSoup(res.content, "html.parser")
        paragraphs = soup.find_all("p")
        content = " ".join([p.get_text() for p in paragraphs]).strip()
        return content[:2000]  # Trim if too long
    except:
        return ""

#  STEP 3: Summarize Article

def summarize_text(text):
    return summarizer(text, max_length=200, min_length=40, do_sample=False)[0]['summary_text']

#  STEP 4: Paraphrase Title

def paraphrase_title(title):
    result = paraphraser(f"paraphrase: {title}", max_length=60, do_sample=True)[0]['generated_text']
    return result

#  STEP 5: Generate Thumbnail via Stable Diffusion API (Colab version uses placeholder)

def generate_placeholder_image(prompt):
    image = pipe(prompt).images[0]
    filename = f"{prompt.replace(' ', '_')[:30]}.png"
    local_path = f"/tmp/{filename}"

    image.save(local_path)
    print(f"✅ Image saved: {local_path}")
    return local_path
   

#  STEP 6: Upload to WordPress

def upload_image(image, title):
    img_bytes = BytesIO()
    image.save(img_bytes, format='PNG')
    img_bytes.seek(0)
    
    credentials = f"{WP_USERNAME}:{WP_APP_PASSWORD}"
    token = base64.b64encode(credentials.encode()).decode("utf-8")
    headers = {
        "Authorization": f"Basic {token}",
        "Content-Disposition": f'attachment; filename="{title[:30]}.png"',
        "Content-Type": "image/png"
    }
    res = requests.post(f"{WP_SITE_URL}/wp-json/wp/v2/media", headers=headers, data=img_bytes)
    return res.json().get("source_url") if res.status_code == 201 else ""

def upload_image_to_wordpress(image_path):
    print(f"Uploading image: {image_path}")
    credentials = f"{WP_USERNAME}:{WP_APP_PASSWORD}"
    token = base64.b64encode(credentials.encode()).decode('utf-8')
    headers = {
        "Authorization": f"Basic {token}",
        "Content-Disposition": f'attachment; filename="{os.path.basename(image_path)}"',
        "Content-Type": "image/png"
    }

    with open(image_path, "rb") as img:
        response = requests.post(
            f"{WP_SITE_URL}/wp-json/wp/v2/media",
            headers=headers,
            data=img
        )
    if response.status_code == 201:
         json_data = response.json()
         return json_data.get("source_url")
        # return response.json().get("source_url")
    else:
        print("❌ Image upload failed:", response.text)
        return None

def get_or_create_tag_id(tag_name):
    token = base64.b64encode(f"{WP_USERNAME}:{WP_APP_PASSWORD}".encode()).decode("utf-8")
    headers = {
        "Authorization": f"Basic {token}",
        "Content-Type": "application/json"
    }

    # Check if tag exists
    search_url = f"{WP_SITE_URL}/wp-json/wp/v2/tags?search={tag_name}"
    response = requests.get(search_url, headers=headers)
    results = response.json()

    if results:
        return results[0]['id']

    # Create the tag if not found
    payload = {"name": tag_name}
    create_response = requests.post(f"{WP_SITE_URL}/wp-json/wp/v2/tags", headers=headers, json=payload)
    
    if create_response.status_code == 201:
        return create_response.json()['id']
    else:
        print("❌ Failed to create tag:", create_response.text)
        return None


# ✅ Final Blog Post

def post_to_wordpress(title, content):
    seo_focus = "AI News Update"
    today = datetime.now().strftime("%B %d, %Y")
    focus_keyword = "AI News"
    tag_ids = [get_or_create_tag_id(focus_keyword)]

    payload = {
        'title': f"{seo_focus}: {title}",
        'content': content,
        'status': 'publish',
        'categories': [NEWS_CATEGORY_ID],  # Change this to your desired category ID
        'tags': tag_ids,
        'excerpt': f"{seo_focus} for {today} – Summarized & Optimized",
    }
    token = base64.b64encode(f"{WP_USERNAME}:{WP_APP_PASSWORD}".encode()).decode()
    headers = {
        "Authorization": f"Basic {token}",
        "Content-Type": "application/json"
    }
    res = requests.post(f"{WP_SITE_URL}/wp-json/wp/v2/posts", headers=headers, json=payload)
    if res.status_code == 201:
        print("✅ Posted:", res.json().get("link"))
    else:
        print("❌ Failed:", res.text)

# Main Execution

def main():
    articles = get_ai_news()
    html_content = ''
    for i, art in enumerate(articles, 1):   
        print(f"Processing: {art['title']}")
        #text = extract_article_text(art['url'])
        text = search_title
        if not text:
            print("⚠️ No valid content.")
            continue
        summary = summarize_text(text)
        new_title = paraphrase_title(art['title'])

        title = 'Automated AI Content Bot: From News to WordPress in Minutes'
        img = generate_placeholder_image(title)
        img_url = upload_image_to_wordpress(img)

        html_content += f"""
            <div style="display: flex; flex-direction: column; gap: 20px; margin-bottom: 40px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #fff; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border-radius: 12px; overflow: hidden;">

            <style>
                @media(min-width: 768px) {{
                .responsive-container {{
                    display: flex;
                    flex-direction: row;
                }}
                .image-block {{
                    flex: 1;
                    max-width: 50%;
                    padding: 16px;
                }}
                .text-block {{
                    flex: 2;
                    padding: 24px;
                }}
                }}
                @media(max-width: 767px) {{
                .responsive-container {{
                    display: flex;
                    flex-direction: column;
                }}
                .image-block, .text-block {{
                    width: 100%;
                    padding: 12px;
                }}
                }}
            </style>

            <div class="responsive-container">
                <!-- Left: Image -->
                {'<div class="image-block"><img src="' + img_url + '" alt="' + new_title + '" style="width: 100%; height: auto; object-fit: cover; border-radius: 10px;" /></div>' if img_url else ''}

                <!-- Right: Text Content -->
                <div class="text-block">
                <h2 style="color: #1e2a38; font-size: 1.4em; margin-top: 0;">🎉 {i}. {new_title}</h2>

                <p>{summary}</p>

                <p style="font-size: 0.9em; margin-top: 20px; color: #666;">
                    📌 <strong>Source:</strong> {art['source']['name']} &nbsp;|&nbsp;
                    <a href="{art['url']}" target="_blank" style="color:#0073aa; text-decoration: underline;">
                    🔗 Original Article
                    </a>
                </p>
                </div>
            </div>
            </div>
            """
      

    today = datetime.now().strftime("%B %d, %Y")
    mblog_title = f"Top AI Breakthroughs You Need to Know – {today}"

    post_to_wordpress(mblog_title, html_content)

if search_title:
 main()
