#!/usr/bin/env python3
"""Search nanpu API for 唐山晟红 notice"""
import requests, json, sys
sys.stdout.reconfigure(encoding='utf-8')

headers = {
    "User-Agent": "Mozilla/5.0",
    "Referer": "https://www.nanpu.gov.cn/news/18/",
    "Accept": "application/json, text/plain, */*"
}
api_url = "https://www.nanpu.gov.cn/fwebapi/cms/lowcode/60003/18505/list?cate=0"
payload = {
    "size": 200,
    "query": [{
        "esField": "DETAIL_ES.es_multi_category_6d5k7017",
        "groupEnd": "1",
        "field": "category_6d5k7017",
        "sourceType": "page",
        "dataType": "array[category]",
        "logic": "and",
        "groupBegin": "1",
        "value": "1628181411606835200",
        "operator": "in"
    }],
    "from": 0,
    "sort": [],
    "_detailId": "1628181411606835200"
}

r = requests.post(api_url, json=payload, headers=headers, timeout=30)
data = r.json()

if data.get("status") == "200":
    items = data["data"].get("list", [])
    print(f"Total items: {len(items)}")
    for item in items:
        title = item.get("title", "")
        if "晟红" in title or "2,4-滴" in title or "滴·氨氯" in title:
            print(f"\nFOUND: {title}")
            item_id = item.get("id", "") or item.get("_id", "")
            print(f"ID: {item_id}")
            detail_url = f"https://www.nanpu.gov.cn/zwxx/{item_id}.html"
            print(f"Detail URL: {detail_url}")
            print(f"Date: {item.get('createTime', '')} / {item.get('publishTime', '')}")
            
            # Fetch detail and check content type
            r2 = requests.get(detail_url, headers=headers, timeout=30)
            r2.encoding = 'utf-8'
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(r2.text, 'html.parser')
            rt = soup.find(class_='e_richText-11')
            if rt:
                imgs = rt.find_all('img')
                ps = rt.find_all('p')
                txt = rt.get_text(strip=True)
                print(f"\n.e_richText-11 content:")
                print(f"  Text: {len(txt)} chars")
                print(f"  Images: {len(imgs)}")
                print(f"  P-tags: {len(ps)}")
                for p in ps:
                    ptxt = p.get_text(strip=True)
                    if ptxt and len(ptxt) > 5:
                        print(f"  <p>: {ptxt[:200]}")
                for img in imgs[:3]:
                    src = img.get('src', '')[:80]
                    alt = img.get('alt', '')[:40]
                    print(f"  <img>: src={src} alt={alt}")
            break
    else:
        print("Not found in first 200 items - try more pages")
else:
    print(f"API error: {data}")
