
import os
import requests
import json
from dotenv import load_dotenv

load_dotenv()

# Check for API Key
NOTION_API_KEY = os.getenv("NOTION_API_KEY")
if not NOTION_API_KEY:
    try:
        with open("/app/n8n_api_Token_git.txt", "r") as f:
            content = f.read()
            if "secret_" in content:
                NOTION_API_KEY = content.strip().split('\n')[0]
    except:
        pass

if not NOTION_API_KEY:
    print("Error: NOTION_API_KEY not found.")
    exit(1)

NOTION_DB_ID = "2ec88f4285448014ab38ea664b4c2b81"
headers = {"Authorization": f"Bearer {NOTION_API_KEY}", "Notion-Version": "2022-06-28", "Content-Type": "application/json"}

targets = [
    "Energy - Grid & Utilities",
    "Tech - Data Center",
    "Retail - Non-Food"
]

def check_vertical(vertical_name):
    print(f"\n--- Checking: {vertical_name} ---")
    url = f"https://api.notion.com/v1/databases/{NOTION_DB_ID}/query"
    payload = {"filter": {"property": "Vertical", "title": {"contains": vertical_name}}}
    resp = requests.post(url, headers=headers, json=payload)
    
    if resp.status_code != 200:
        print(f"Error: {resp.text}")
        return

    results = resp.json().get("results", [])
    if not results:
        print("Not found.")
        return
    
    page = results[0]
    props = page["properties"]
    
    # Check Pains (Start)
    pains = props.get("Pains", {}).get("rich_text", [])
    pains_text = "".join([t["text"]["content"] for t in pains])
    print(f"PAINS (First 100 chars): {pains_text[:100]}...")
    
    # Check Gains (Start)
    gains = props.get("Gains", {}).get("rich_text", [])
    gains_text = "".join([t["text"]["content"] for t in gains])
    print(f"GAINS (First 100 chars): {gains_text[:100]}...")
    
    # Check Ops Focus Secondary
    ops_focus = props.get("Ops Focus: Secondary", {}).get("checkbox", False)
    print(f"Ops Focus Secondary: {ops_focus}")
    
    # Check Secondary Product
    sec_prod_rel = props.get("Secondary Product", {}).get("relation", [])
    if sec_prod_rel:
        prod_id = sec_prod_rel[0]["id"]
        # Fetch Product Name
        prod_url = f"https://api.notion.com/v1/pages/{prod_id}"
        prod_resp = requests.get(prod_url, headers=headers)
        if prod_resp.status_code == 200:
            prod_props = prod_resp.json()["properties"]
            # Try to find Name/Title
            # Usually "Name" or "Product Name"
            # Let's look for title type
            prod_name = "Unknown"
            for k, v in prod_props.items():
                if v["type"] == "title":
                     prod_name = "".join([t["text"]["content"] for t in v["title"]])
            print(f"Secondary Product: {prod_name}")
        else:
            print(f"Secondary Product ID: {prod_id} (Could not fetch name)")
    else:
        print("Secondary Product: None")

for t in targets:
    check_vertical(t)
