"""Quick API test for backend."""
import json
import urllib.request

BASE = "http://127.0.0.1:8000"

def req(method, path, data=None):
    url = BASE + path
    body = json.dumps(data).encode() if data else None
    r = urllib.request.Request(url, data=body, method=method)
    r.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(r) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        return {"error": e.code, "body": e.read().decode()}

# 1. Health
print("=== Health ===")
print(req("GET", "/api/health"))

# 2. Create project
print("\n=== Create Project ===")
proj = req("POST", "/api/projects", {
    "name": "MARS Airgap Optimization",
    "topology": "SSSR",
    "description": "Test project for P2-M1 API validation",
    "model_path": "models/MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot",
    "boundary_conditions": {"outer_diameter_mm": 76, "speed_rpm": 5000, "current_a": 21},
})
print(json.dumps(proj, indent=2))
proj_id = proj.get("id")

# 3. List projects
print("\n=== List Projects ===")
print(req("GET", "/api/projects"))

# 4. Create plan
print("\n=== Create Plan ===")
plan_data = {
    "plan_id": "SP-TEST-001",
    "model_path": "models/MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot",
    "topology": "SSSR",
    "variables": [
        {"name": "Airgap", "display_name": "Airgap", "unit": "mm", "values": [0.6, 1.0, 1.5]}
    ],
    "cases": [],
}
plan = req("POST", "/api/plans", {
    "project_id": proj_id,
    "name": "Airgap Scan 0.6-1.5mm",
    "plan_data": plan_data,
    "notes": "Test plan for API validation",
})
print(json.dumps(plan, indent=2))
plan_id = plan.get("id")
plan_uuid = plan.get("plan_id")

# 5. Download plan
print("\n=== Download Plan ===")
dl = req("GET", f"/api/plans/{plan_id}/download")
print(f"plan_id: {dl.get('plan_id')}")
print(f"variables: {dl.get('plan_data', {}).get('variables')}")

# 6. Download by UUID
print("\n=== Download by UUID ===")
dl2 = req("GET", f"/api/plans/by-plan-id/{plan_uuid}/download")
print(f"plan_id: {dl2.get('plan_id')}")

# 7. List plans
print("\n=== List Plans ===")
plans = req("GET", f"/api/plans?project_id={proj_id}")
print(f"total: {plans.get('total')}")

print("\n=== ALL API TESTS PASSED ===")
