import os
import requests
import json
from dotenv import load_dotenv

load_dotenv()

NOTION_API_KEY = os.getenv("NOTION_API_KEY")
NOTION_DB_ID = "2ec88f4285448014ab38ea664b4c2b81"

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

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

def get_vertical_details(vertical_name_contains):
    url = f"https://api.notion.com/v1/databases/{NOTION_DB_ID}/query"
    payload = {
        "filter": {
            "property": "Vertical",
            "title": {
                "contains": vertical_name_contains
            }
        }
    }
    
    response = requests.post(url, headers=headers, json=payload)
    if response.status_code != 200:
        print(f"Error: {response.status_code}")
        return

    results = response.json().get("results", [])
    if not results:
        print(f"❌ No entry found containing '{vertical_name_contains}'")
        return

    for page in results:
        props = page["properties"]
        
        # safely extract title
        title_list = props.get("Vertical", {}).get("title", [])
        title = title_list[0]["plain_text"] if title_list else "Unknown Title"
        
        # Pains
        pains_list = props.get("Pains", {}).get("rich_text", [])
        pains = pains_list[0]["plain_text"] if pains_list else "N/A"
        
        # Gains
        gains_list = props.get("Gains", {}).get("rich_text", [])
        gains = gains_list[0]["plain_text"] if gains_list else "N/A"
        
        # Ops Focus
        ops_focus = props.get("Ops Focus: Secondary", {}).get("checkbox", False)
        
        # Products
        # Primary is select
        pp_select = props.get("Primary Product Category", {}).get("select")
        pp = pp_select["name"] if pp_select else "N/A"
        
        # Secondary is select
        sp_select = props.get("Secondary Product", {}).get("select")
        sp = sp_select["name"] if sp_select else "N/A"

        print(f"\n🔹 VERTICAL: {title}")
        print(f"   Primary: {pp}")
        print(f"   Secondary: {sp}")
        print(f"   Ops Focus Secondary? {'✅ YES' if ops_focus else '❌ NO'}")
        print(f"   PAINS:\n   {pains}")
        print(f"   GAINS:\n   {gains}")
        print("-" * 40)

targets = [
    "Hospital", 
    "Hotel", 
    "Logistics", 
    "Manufacturing", 
    "Retail",
    "Facility Management" 
]

for t in targets:
    get_vertical_details(t)
