# python script to parte articles from Detroit, Chicago and Dallas news feeds
# must first install newspaper
# pip install newspaper#
# pip3 install newspaper3k
# pip install requests beautifulsoup4

# uset wget get to download the image associated with the story
#wget -O image-file.jpg "https://images.foxtv.com/static.fox2detroit.com/www.fox2detroit.com/content/uploads/2020/11/1280/720/wjbk-vehicles-stolen-112320.jpg?ve=1\u0026tl=1"

#pass in the url link to the story
# e.g. "https://www.fox2detroit.com/news/detroit-police-investigating-multi-car-theft-at-east-side-dealership"


# start exection of script
#parse-detroit-articles.py ""https://www.fox2detroit.com/news/detroit-police-investigating-multi-car-theft-at-east-side-dealership"" "output-file.caption"

#python.exe add-overflow-lite.py https://www.audacy.com/wwjnewsradio/news/local/macomb-man-charged-in-deadly-2022-detroit-mass-shooting?fbclid=IwZXh0bgNhZW0CMTEAAR3toSbLmsyUsgId5Pgs7Wobd_Z6lY_kuUNcxIPdQLlgy1IoSVtreDGqpVs_aem_AReQiAxjdBjGXz_iN2HWUTCMYVe2bEhsm7WMeVy6jvILfB0tyz3ZWpQZB1BL8Q-pzcKHsUdivw_DXvUhQ8EegWQy

print("\n")
print("ENTERING PYTHON date-published-crimewatch-articles")
print("\n")

import sys
import os
from newspaper import Article
import requests
import json
from bs4 import BeautifulSoup

#DBUG=sys.argv[2]
#print("DEBUG-MODE=",DBUG)

# url = "https://www.nbcmiami.com/news/local/3-reported-shot-in-liberty-city/1972050/"

# https://www.local10.com/news/local/2025/05/28/miami-dade-tow-yard-was-also-an-illegal-chop-shop-cops-say/
# https://www.nbcdfw.com/news/local/man-stabbed-beheaded-machete-dallas-motel/3916937/
# https://www.clickondetroit.com/video/news/2026/03/12/child-predator-gets-decades-for-years-of-abuse-killing-of-13-year-old-naziyah-harris/
# https://www.clickondetroit.com/news/2015/09/19/woman-killed-in-boating-collision-on-lake-st-clair/

url=sys.argv[1]
print("\nURL=",url)

headers = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/120.0.0.0 Safari/537.36"
    )
}


def extract_article_info(url):

    article = {
        "headline": None,
        "published_date": None,
        "modified_date": None,
        "url": url
    }

    try:

        response = requests.get(
            url,
            headers=headers,
            timeout=20
        )

        response.raise_for_status()

        soup = BeautifulSoup(
            response.text,
            "html.parser"
        )

        # ------------------------------------------
        # 1. Extract headline
        # ------------------------------------------

        headline = None

        # Open Graph headline
        og_title = soup.find(
            "meta",
            property="og:title"
        )

        if og_title:
            headline = og_title.get("content")

        # Twitter headline fallback
        if not headline:

            twitter_title = soup.find(
                "meta",
                attrs={"name": "twitter:title"}
            )

            if twitter_title:
                headline = twitter_title.get("content")

        # HTML title fallback
        if not headline:

            if soup.title:
                headline = soup.title.get_text(
                    strip=True
                )

        article["headline"] = headline

        # ------------------------------------------
        # 2. Extract JSON-LD structured data
        # ------------------------------------------

        scripts = soup.find_all(
            "script",
            type="application/ld+json"
        )

        def process_jsonld(data):

            if isinstance(data, dict):

                # Extract headline
                if not article["headline"]:
                    article["headline"] = data.get(
                        "headline"
                    ) or data.get("name")

                # Extract published date
                if not article["published_date"]:
                    article["published_date"] = data.get(
                        "datePublished"
                    )

                # Extract modified date
                if not article["modified_date"]:
                    article["modified_date"] = data.get(
                        "dateModified"
                    )

                # Check nested graph
                if "@graph" in data:

                    for item in data["@graph"]:
                        process_jsonld(item)

            elif isinstance(data, list):

                for item in data:
                    process_jsonld(item)

        for script in scripts:

            try:

                json_data = json.loads(
                    script.string or script.get_text()
                )

                process_jsonld(json_data)

            except (json.JSONDecodeError, TypeError):
                continue

        # ------------------------------------------
        # 3. Extract publication metadata
        # ------------------------------------------

        published_meta = [
            ("property", "article:published_time"),
            ("property", "og:published_time"),
            ("name", "datePublished"),
            ("name", "pubdate"),
            ("name", "publishdate"),
            ("name", "publication_date"),
            ("name", "date")
        ]

        for attribute, value in published_meta:

            if article["published_date"]:
                break

            tag = soup.find(
                "meta",
                attrs={attribute: value}
            )

            if tag and tag.get("content"):

                article["published_date"] = (
                    tag.get("content")
                )

        # ------------------------------------------
        # 4. Extract modified metadata
        # ------------------------------------------

        modified_meta = [
            ("property", "article:modified_time"),
            ("property", "og:updated_time"),
            ("name", "dateModified"),
            ("name", "lastModified"),
            ("name", "last-modified"),
            ("name", "modified")
        ]

        for attribute, value in modified_meta:

            if article["modified_date"]:
                break

            tag = soup.find(
                "meta",
                attrs={attribute: value}
            )

            if tag and tag.get("content"):

                article["modified_date"] = (
                    tag.get("content")
                )

        # ------------------------------------------
        # 5. Extract HTML TIME tags
        # ------------------------------------------

        for tag in soup.find_all("time"):

            date_value = tag.get("datetime")

            if not date_value:
                continue

            # Look for publication date
            if not article["published_date"]:

                article["published_date"] = (
                    date_value
                )

            # Look for updated date
            if not article["modified_date"]:

                text = tag.get_text(
                    strip=True
                ).lower()

                if "updated" in text:

                    article["modified_date"] = (
                        date_value
                    )

        # ------------------------------------------
        # 6. Final results
        # ------------------------------------------

        return article

    except requests.RequestException as e:

        article["error"] = str(e)

        return article


# ==============================================
# RUN SCRIPT
# ==============================================

result = extract_article_info(url)

print("=" * 60)
print("ARTICLE INFORMATION")
print("=" * 60)

print("Headline:", result["headline"])
print("Published:", result["published_date"])
print("Modified:", result["modified_date"])
print("URL:", result["url"])

if "error" in result:
    print("ERROR:", result["error"])

with open("article_info.json", "w", encoding="utf-8") as f:
    json.dump(
        result,
        f,
        indent=4,
        ensure_ascii=False
    )

print("\nSaved to article_info.json")
print("\nLEAVING PYTHON date-published-crimewatch-articles")
print("\n")



