import requests
import logging
from config import WP_URL, WP_USERNAME, WP_APP_PASSWORD

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def create_wp_page(title, content, slug):
    """
    Creates a static page in WordPress using the REST API.
    """
    pages_url = f"{WP_URL.rstrip('/')}/wp-json/wp/v2/pages"
    auth = (WP_USERNAME, WP_APP_PASSWORD)
    
    # Check if page already exists to update it
    try:
        check_resp = requests.get(pages_url, params={"slug": slug, "status": "any"}, auth=auth, timeout=15)
        if check_resp.status_code == 200 and check_resp.json():
            page_id = check_resp.json()[0]["id"]
            logging.info(f"Page '{title}' (slug: {slug}) already exists (ID: {page_id}). Updating content...")
            update_url = f"{pages_url}/{page_id}"
            update_payload = {
                "title": title,
                "content": content,
                "status": "publish"
            }
            update_resp = requests.post(update_url, json=update_payload, auth=auth, timeout=20)
            if update_resp.status_code == 200:
                logging.info(f"Successfully updated page: '{title}'")
                return update_resp.json()
            else:
                logging.error(f"Failed to update page '{title}'. Status: {update_resp.status_code}")
                return check_resp.json()[0]
    except Exception as e:
        logging.warning(f"Error checking or updating page existence: {e}")

    payload = {
        "title": title,
        "content": content,
        "slug": slug,
        "status": "publish",
        "comment_status": "closed",
        "ping_status": "closed"
    }
    
    try:
        response = requests.post(pages_url, json=payload, auth=auth, timeout=20)
        if response.status_code in [200, 201]:
            result = response.json()
            logging.info(f"Successfully created page: '{title}' (Link: {result.get('link')})")
            return result
        else:
            logging.error(f"Failed to create page '{title}'. Status: {response.status_code}, Response: {response.text}")
            return None
    except Exception as e:
        logging.error(f"Error posting page to WordPress: {e}")
        return None

# Page Contents formatted in professional HTML
privacy_policy_html = """
<h2>Privacy Policy</h2>
<p>Last updated: June 19, 2026</p>
<p>At our Tech News platform, accessible from our website, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by our site and how we use it.</p>

<h3>Log Files</h3>
<p>We follow a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services' analytics. The information collected by log files includes internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users' movement on the website, and gathering demographic information.</p>

<h3>Cookies and Web Beacons</h3>
<p>Like any other website, we use "cookies". These cookies are used to store information including visitors' preferences, and the pages on the website that the visitor accessed or visited. The information is used to optimize the users' experience by customizing our web page content based on visitors' browser type and/or other information.</p>

<h3>Google DoubleClick DART Cookie</h3>
<p>Google is one of a third-party vendor on our site. It also uses cookies, known as DART cookies, to serve ads to our site visitors based upon their visit to our site and other sites on the internet. However, visitors may choose to decline the use of DART cookies by visiting the Google ad and content network Privacy Policy at the following URL – <a href="https://policies.google.com/technologies/ads">https://policies.google.com/technologies/ads</a></p>

<h3>Our Advertising Partners</h3>
<p>Some of advertisers on our site may use cookies and web beacons. Our advertising partners include:</p>
<ul>
    <li><strong>Google AdSense</strong></li>
</ul>
<p>Each of our advertising partners has their own Privacy Policy for their policies on user data. For easier access, we hyperlinked to their Privacy Policies above.</p>

<h3>Third Party Privacy Policies</h3>
<p>Our Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options.</p>
<p>You can choose to disable cookies through your individual browser options. To know more detailed information about cookie management with specific web browsers, it can be found at the browsers' respective websites.</p>

<h3>Children's Information</h3>
<p>Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity.</p>
<p>We do not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.</p>

<h3>Consent</h3>
<p>By using our website, you hereby consent to our Privacy Policy and agree to its Terms and Conditions.</p>
"""

terms_of_service_html = """
<h2>Terms of Service</h2>
<p>Last updated: June 19, 2026</p>
<p>Welcome to America Express News. These terms and conditions outline the rules and regulations for the use of our Website, which covers general news, sports, soccer, entertainment, health, lifestyle, events, finance &amp; crypto, gaming &amp; esports, travel &amp; food, and strange &amp; viral stories across the United States.</p>

<h3>Acceptance of Terms</h3>
<p>By accessing this website, we assume you accept these terms and conditions in full. Do not continue to use this website if you do not accept all of the terms and conditions stated on this page.</p>

<h3>Cookies</h3>
<p>We employ the use of cookies. By using our website you consent to the use of cookies in accordance with our privacy policy. Most of the modern day interactive web sites use cookies to enable us to retrieve user details for each visit.</p>

<h3>License and Intellectual Property</h3>
<p>Unless otherwise stated, we and/or our licensors own the intellectual property rights for all material on this site. All intellectual property rights are reserved. You may view and/or print pages from this site for your own personal use subject to restrictions set in these terms and conditions.</p>
<p>You must not:</p>
<ul>
    <li>Republish material from this site</li>
    <li>Sell, rent or sub-license material from this site</li>
    <li>Reproduce, duplicate or copy material from this site</li>
</ul>

<h3>User Comments and Content</h3>
<p>This Agreement shall begin on the date hereof. Certain parts of this website offer the opportunity for users to post and exchange opinions, information, material and data ('Comments'). We do not screen, edit, publish or review Comments prior to their appearance on the website and Comments do not reflect the views or opinions of our platform, its agents or affiliates.</p>

<h3>Disclaimer of Liability</h3>
<p>To the maximum extent permitted by applicable law, we exclude all representations, warranties and conditions relating to our website and the use of this website. Nothing in this disclaimer will limit or exclude our or your liability for death or personal injury resulting from negligence, limit or exclude our or your liability for fraud or fraudulent misrepresentation, or exclude any of our or your liabilities that may not be excluded under applicable law.</p>
"""

disclaimer_html = """
<h2>Disclaimer</h2>
<p>Last updated: June 19, 2026</p>
<p>The information contained in this website is for general information purposes only. The information is provided by our Tech News platform and while we endeavor to keep the information up to date and correct, we make no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the website or the information, products, services, or related graphics contained on the website for any purpose. Any reliance you place on such information is therefore strictly at your own risk.</p>

<h3>Professional Disclaimer</h3>
<p>In no event will we be liable for any loss or damage including without limitation, indirect or consequential loss or damage, or any loss or damage whatsoever arising from loss of data or profits arising out of, or in connection with, the use of this website.</p>

<h3>External Links Disclaimer</h3>
<p>Through this website, you are able to link to other websites which are not under our control. We have no control over the nature, content and availability of those sites. The inclusion of any links does not necessarily imply a recommendation or endorse the views expressed within them.</p>

<h3>Website Availability</h3>
<p>Every effort is made to keep the website up and running smoothly. However, we take no responsibility for, and will not be liable for, the website being temporarily unavailable due to technical issues beyond our control.</p>
"""

about_us_html = """
<h2>About Us</h2>
<p>Welcome to America Express News, your premier destination for timely, accurate, and comprehensive news coverage across the United States. We deliver the latest updates and in-depth stories across a diverse range of topics, keeping you informed and connected to the heartbeat of the nation.</p>
<p>Our coverage spans multiple specialized sections designed to cater to all your informational needs:</p>
<ul>
    <li><strong>Latest News:</strong> Up-to-the-minute updates on breaking national events, tech innovations, and critical announcements.</li>
    <li><strong>Sports &amp; Soccer:</strong> Comprehensive coverage of American sports, game analyses, team updates, and detailed reports from the soccer field and beyond.</li>
    <li><strong>Entertainment:</strong> The latest from Hollywood, music, pop culture, and major US media developments.</li>
    <li><strong>Lifestyle &amp; Health:</strong> Insights, expert advice, and modern trends in healthy living, wellness, and everyday American life.</li>
    <li><strong>Events:</strong> Coverage of major national events, cultural gatherings, and conferences shaping local communities.</li>
    <li><strong>Finance &amp; Crypto:</strong> Updates on personal finance, stock market trends, investments, and cryptocurrency markets.</li>
    <li><strong>Gaming &amp; Esports:</strong> Video game reviews, industry news, console/PC hardware updates, and competitive esports coverage.</li>
    <li><strong>Travel &amp; Food:</strong> Travel guides, destination reviews, culinary discoveries, and food culture from around the US.</li>
    <li><strong>Strange &amp; Viral:</strong> Unexplained occurrences, oddities, viral trends, and heartwarming human-interest stories.</li>
</ul>
<p>Driven by professional editorial integrity and supported by modern news-gathering workflows, we transform complex events into clear, insightful, and highly readable stories. Whether you are browsing our Home page for a quick morning digest or diving deep into specific categories, we ensure you stay ahead in today's fast-moving information landscape.</p>
<p>We hope you enjoy our daily news digests as much as we enjoy presenting them to you. For any questions, suggestions, or editorial feedback, please feel free to contact us.</p>
<p>Sincerely,<br/>The America Express News Editorial Team</p>
"""

contact_us_html = """
<h2>Contact Us</h2>
<p>If you have any questions, suggestions, or would like to request more information about our platform, please feel free to reach out to us. We value your feedback and aim to respond to all inquiries within 24-48 hours.</p>

<h3>Contact Details</h3>
<ul>
    <li><strong>Email:</strong> <a href="mailto:travelspotsdaily@gmail.com">travelspotsdaily@gmail.com</a></li>
    <li><strong>Office Hours:</strong> Monday – Friday, 9:00 AM – 5:00 PM</li>
    <li><strong>Address:</strong> New York, USA</li>
</ul>

<p>For press inquiries, advertising proposals, or copyright issues, please specify the subject in your email for a faster response.</p>
"""

def create_all_policies():
    logging.info("Starting the creation of AdSense policy pages...")
    create_wp_page("Privacy Policy", privacy_policy_html, "privacy-policy")
    create_wp_page("Terms of Service", terms_of_service_html, "terms-of-service")
    create_wp_page("Disclaimer", disclaimer_html, "disclaimer")
    create_wp_page("About Us", about_us_html, "about-us")
    create_wp_page("Contact Us", contact_us_html, "contact-us")
    logging.info("Finished creating all policy pages.")

if __name__ == "__main__":
    create_all_policies()
