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lyMWzfoeuIGhvCKuDiJeVw2c0r2UZFpHqjnfhXcb0_aacukXe8z-srj8-Rdw"

base = "https://pashub.net/api"

headers = {"Authorization": f"Bearer {TOKEN}", "Accept": "application/json"}

company_id = "cb5249e2-8f31-4ef4-aefd-08ddaccb1fa2"

# 1️⃣ get jobs
params = {
    "pageIndex": 0,
    "pageSize": 20,
    "orderBy": "createdUtc",
    "orderDesc": "true",
    "addressUprn": "100061885568",
    "companyId": company_id,
}

r = requests.get(f"{base}/jobs", headers=headers, params=params)

payload = r.json()

property_id = payload["results"][0]["id"]

print("JOB:", property_id)

# 2️⃣ get evidence list
r = requests.get(f"{base}/jobs/{property_id}/evidence", headers=headers)

print(r.status_code)

evidence = r.json()

print(evidence)


# 3️⃣ get evidence metadata

if evidence:
    evidence_id = evidence["results"][0]["fileId"]

    meta_url = f"https://pashub.net/api/jobs/{property_id}/evidenceMetadata"

    meta_params = {"evidenceIds": evidence_id}

    r = requests.get(meta_url, headers=headers, params=meta_params)
    r.raise_for_status()

    meta = r.json()

    container = meta["containerName"]
    blob_uri = meta["blobUri"]

    file = meta["files"][0]
    file_id = file["fileId"]
    file_name = file["fileName"]

    base, sas = blob_uri.split("?", 1)

    download_url = f"{base}{container}/{file_id}?{sas}"

    print("Download URL:", download_url)

    pdf = requests.get(download_url)
    pdf.raise_for_status()

    with open(file_name, "wb") as f:
        f.write(pdf.content)

    print("Saved:", file_name)
