﻿import requests
from bs4 import BeautifulSoup
from datetime import datetime
import ssl
from urllib3 import poolmanager
from requests.adapters import HTTPAdapter
import os
print("=== DEBUG INFO ===")
print("Current working directory:", os.getcwd())
print("Script location:", os.path.abspath(__file__))
print("User running this script:", os.getenv("USER"))
print("===================")

# --- CONFIG ---
OUTPUT_DIR = "home/directobjective/bk.directobjective.com/auto/output"
if not os.path.exists(OUTPUT_DIR):
    print("⚠️ Output directory not found:", OUTPUT_DIR)
else:
    print("✅ Output directory confirmed:", OUTPUT_DIR)
os.makedirs(OUTPUT_DIR, exist_ok=True)  # ensure directory exists
filename = os.path.join(OUTPUT_DIR, "ResultsGrid_ExportData.csv")

# Custom adapter to allow weaker ciphers
class SSLAdapter(HTTPAdapter):
    def __init__(self, **kwargs):
        self.ssl_context = ssl.create_default_context()
        self.ssl_context.set_ciphers('DEFAULT:@SECLEVEL=1')
        super().__init__(**kwargs)

    def init_poolmanager(self, *args, **kwargs):
        kwargs['ssl_context'] = self.ssl_context
        return super().init_poolmanager(*args, **kwargs)

# Session to maintain cookies
session = requests.Session()
session.mount("https://", SSLAdapter())

url = "https://members.payroll.ca/CPA21-EN/PubliciQA.aspx"

# Step 1: GET the page
r = session.get(url)
soup = BeautifulSoup(r.text, "html.parser")

# Extract hidden fields
data = {}
for hidden in soup.find_all("input", type="hidden"):
    data[hidden.get("name")] = hidden.get("value", "")

# Step 2: Set the __EVENTTARGET to simulate CSV button click
data["__EVENTTARGET"] = "ctl00$TemplateBody$WebPartManager1$gwpciNewQueryMenuCommon$ciNewQueryMenuCommon$ResultsGrid$btnExportCSV"
data["__EVENTARGUMENT"] = ""

# POST to download CSV
csv_response = session.post(url, data=data)

print("Attempting to save file to:", filename)

# Save CSV file
with open(filename, "wb") as f:
    f.write(csv_response.content)

print(f"CSV saved as {filename}")