import requests
import json
import urllib.request
import urllib.parse

BASE_URL = 'http://127.0.0.1:8000'

def run_tests():
    print("=== STARTING FULL INTEGRATION TESTS (ORIGINAL KM-1 PIPELINE) ===")

    # 1. Presets
    r_presets = requests.get(f"{BASE_URL}/api/presets")
    print(f"1. GET /api/presets -> Status: {r_presets.status_code}")
    assert r_presets.status_code == 200
    presets = r_presets.json()
    print(f"   Modes: {[m['name'] for m in presets['print_modes']]}")

    # 2. TIFF Estimation with EUR currency
    with open("Trial TIF Data/2_585x750_car_300dpi.tif", "rb") as f:
        files = {"file": ("car_sample.tif", f, "image/tiff")}
        data = {
            "mode": 1,
            "media": 1,
            "quality": 1,
            "dpi": 300,
            "use_icc": True,
            "quantity": 5000,
            "duplex": False,
            "cost_cyan": 120.0,
            "cost_magenta": 120.0,
            "cost_yellow": 120.0,
            "cost_black": 100.0,
            "currency": "EUR",
            "currency_symbol": "€"
        }
        r_est = requests.post(f"{BASE_URL}/api/estimate", files=files, data=data)

    print(f"2. POST /api/estimate (TIFF, EUR) -> Status: {r_est.status_code}")
    assert r_est.status_code == 200
    res_data = r_est.json()
    sc = res_data["single_copy_metrics"]
    ca = res_data["cost_analysis"]
    cov = res_data["coverage_percentages"]
    sym = res_data["parameters"]["currency_symbol"]
    print(f"   Currency: {res_data['parameters']['currency']} ({sym})")
    print(f"   Single Copy Total Ink: {sc['total_ml']} ml ({sc['total_grams']} g)")
    print(f"   Job Total Cost (5k copies): {sym}{ca['total_job_cost']:.2f}")
    print(f"   Coverage: C={cov['cyan_pct']}% M={cov['magenta_pct']}% Y={cov['yellow_pct']}% K={cov['black_pct']}%")

    # 3. PDF Estimation with Duplex (Multi-page)
    with open("InkEstimationTool_20092024.pdf", "rb") as f:
        files = {"file": ("manual.pdf", f, "application/pdf")}
        data["quantity"] = 1000
        data["dpi"] = 150
        data["duplex"] = True
        r_pdf = requests.post(f"{BASE_URL}/api/estimate", files=files, data=data)

    print(f"3. POST /api/estimate (PDF, Duplex) -> Status: {r_pdf.status_code}")
    assert r_pdf.status_code == 200
    pdf_res = r_pdf.json()
    p_ca = pdf_res["cost_analysis"]
    p_jt = pdf_res["job_totals"]
    print(f"   PDF Page Count: {pdf_res['document']['page_count']} pages")
    print(f"   Physical Sheets per Book: {pdf_res['document']['sheets_per_copy']} sheets (Duplex)")
    print(f"   Total Physical Sheets for Job: {p_jt['total_physical_sheets']:,} sheets")
    print(f"   Cost per Copy: {sym}{p_ca['cost_per_copy']:.4f}")
    print(f"   Cost per Page Side: {sym}{p_ca['cost_per_page']:.4f}")
    print(f"   Cost per Physical Sheet: {sym}{p_ca['cost_per_sheet']:.4f}")
    print(f"   PDF Job Cost (1k copies): {sym}{p_ca['total_job_cost']:.2f}")

    # 4. PDF Export
    r_exp_pdf = requests.post(f"{BASE_URL}/api/export/pdf", json=res_data)
    print(f"4. POST /api/export/pdf -> Status: {r_exp_pdf.status_code}, Length: {len(r_exp_pdf.content)} bytes")
    assert r_exp_pdf.status_code == 200
    assert r_exp_pdf.content.startswith(b"%PDF")

    # 5. Excel Export
    r_exp_xlsx = requests.post(f"{BASE_URL}/api/export/xlsx", json=res_data)
    print(f"5. POST /api/export/xlsx -> Status: {r_exp_xlsx.status_code}, Length: {len(r_exp_xlsx.content)} bytes")
    assert r_exp_xlsx.status_code == 200
    assert r_exp_xlsx.content.startswith(b"PK")

    print("\n>>> ALL 5 INTEGRATION TESTS COMPLETED SUCCESSFULLY! <<<")

if __name__ == "__main__":
    run_tests()
