"""AstroNirnay Developer API client for Python. No dependencies, Python 3.7+.

Generated from https://api.astronirnay.com/v1/openapi.json, so it always matches the live API.

    from astronirnay import AstroNirnay, AstroNirnayError

    client = AstroNirnay("YOUR_API_KEY")
    chart = client.chart({"birth": {"date": "1990-05-15", "time": "10:30",
                          "latitude": 19.076, "longitude": 72.8777, "timezone": "Asia/Kolkata"}})
    print(chart["ascendant"]["sign"], client.credits_remaining)

Time is 24-hour (HH:MM). Keep your key on the server, never in a mobile or browser app.
"""
import json
import time
import urllib.error
import urllib.parse
import urllib.request

DEFAULT_BASE_URL = "https://api.astronirnay.com/v1"


class AstroNirnayError(Exception):
    """Raised for any error response. Fields: status, code, message, details, request_id."""

    def __init__(self, status, code, message, details=None, request_id=None):
        super().__init__("[%s] %s: %s" % (status, code, message))
        self.status = status
        self.code = code
        self.message = message
        self.details = details or []
        self.request_id = request_id


class AstroNirnay:
    """Client. Every method returns the response "data" object or raises AstroNirnayError."""

    def __init__(self, api_key, base_url=DEFAULT_BASE_URL, timeout=30, max_retries=3):
        if not api_key:
            raise ValueError("api_key is required")
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.max_retries = max_retries
        self.credits_remaining = None  # from the X-Credits-Remaining header of the last call
        self.last_request_id = None

    def _request(self, method, path, body=None, query=None, secured=True):
        url = self.base_url + path
        if query:
            q = {k: v for k, v in query.items() if v is not None}
            if q:
                url += "?" + urllib.parse.urlencode(q)
        data = json.dumps(body).encode("utf-8") if body is not None else None
        headers = {"Accept": "application/json", "User-Agent": "astronirnay-python/1.0"}
        if data is not None:
            headers["Content-Type"] = "application/json"
        if secured:
            headers["x-api-key"] = self.api_key
        attempt = 0
        while True:
            req = urllib.request.Request(url, data=data, headers=headers, method=method)
            try:
                with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                    return self._handle(resp.status, resp.headers, resp.read())
            except urllib.error.HTTPError as err:
                raw = err.read()
                if err.code in (429, 502, 503, 504) and attempt < self.max_retries:
                    attempt += 1
                    try:
                        wait = float(err.headers.get("Retry-After", ""))
                    except ValueError:
                        wait = min(2 ** attempt, 8)
                    time.sleep(wait)
                    continue
                return self._handle(err.code, err.headers, raw)

    def _handle(self, status, headers, raw):
        remaining = headers.get("X-Credits-Remaining")
        if remaining is not None:
            try:
                self.credits_remaining = int(remaining)
            except ValueError:
                pass
        text = raw.decode("utf-8", "replace")
        if "json" not in (headers.get("Content-Type") or ""):
            if status >= 400:
                raise AstroNirnayError(status, "http_error", text[:200])
            return text
        try:
            payload = json.loads(text)
        except ValueError:
            raise AstroNirnayError(status, "bad_response", "The server did not return valid JSON")
        meta = payload.get("meta") or {}
        self.last_request_id = meta.get("request_id")
        if status >= 400 or not payload.get("success"):
            err = payload.get("error") or {}
            raise AstroNirnayError(status, err.get("code", "error"), err.get("message", "Request failed"), err.get("details"), self.last_request_id)
        return payload.get("data")

    def chart(self, body):
        """Complete birth chart.

        POST /v1/chart

        Ascendant, all nine planets with sign, degree, nakshatra, pada, dignity, retrograde and combustion flags, the twelve houses, and optional divisional charts (`divisions`: D1, D2, D3, D4, D6, D7, D9, D10, D12, D16, D20, D24, D27, D30, D40, D45, D60).

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "options": {
        "house_system": "whole_sign"
      },
      "divisions": [
        "D9",
        "D10"
      ]
    }
        """
        return self._request("POST", "/chart", body=body, secured=True)

    def planets(self, body):
        """Planet positions.

        POST /v1/planets

        Sidereal positions of the Sun, Moon, Mars, Mercury, Jupiter, Venus, Saturn, Rahu and Ketu.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      }
    }
        """
        return self._request("POST", "/planets", body=body, secured=True)

    def houses(self, body):
        """Houses and occupants.

        POST /v1/houses

        Twelve houses under `whole_sign` (default) or `equal_house`, with the planets in each.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "options": {
        "house_system": "equal_house"
      }
    }
        """
        return self._request("POST", "/houses", body=body, secured=True)

    def dasha_vimshottari(self, body):
        """Vimshottari dasha.

        POST /v1/dasha/vimshottari

        Balance at birth, the running mahadasha → prana chain at `at` (up to `depth` levels, default 3, max 5) and the nested period timeline (`periods_depth` 0–3, default 2) for up to 120 years.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "at": "2026-10-07",
      "depth": 5,
      "periods_depth": 2
    }
        """
        return self._request("POST", "/dasha/vimshottari", body=body, secured=True)

    def panchang(self, body):
        """Daily panchang.

        POST /v1/panchang

        Weekday, sunrise/sunset, moonrise/moonset, tithi, nakshatra, yoga and karana with exact start and end times (as they stand at sunrise, plus every one running during the day), Rahu kaal, Yamaganda, Gulika kaal and Abhijit muhurta.

        Example body:
            {
      "date": "2026-10-07",
      "latitude": 19.076,
      "longitude": 72.8777,
      "timezone": "Asia/Kolkata"
    }
        """
        return self._request("POST", "/panchang", body=body, secured=True)

    def doshas_sade_sati(self, body):
        """Sade Sati and Dhaiya.

        POST /v1/doshas/sade-sati

        Whether Saturn is currently over the 12th, 1st or 2nd sign from the natal Moon (sade sati) or the 4th/8th (dhaiya), the current period and cycle, the next cycle, and a lifetime timeline (`timeline_years`, default 90; set `include_timeline` false to skip it).

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "at": "2026-10-07"
    }
        """
        return self._request("POST", "/doshas/sade-sati", body=body, secured=True)

    def doshas_manglik(self, body):
        """Manglik dosha.

        POST /v1/doshas/manglik

        Mars position from Lagna, Moon and Venus, whether the chart is Manglik, severity, the cancellation rules that apply, and the Navamsa position. The rule set is published in the response (`rules`).

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      }
    }
        """
        return self._request("POST", "/doshas/manglik", body=body, secured=True)

    def matching_ashtakoot(self, body):
        """Ashtakoot matching.

        POST /v1/matching/ashtakoot

        Eight koota scores (36 points), percentage, verdict band, nadi and bhakoot doshas, and manglik compatibility between a groom and a bride.

        Example body:
            {
      "groom": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "bride": {
        "date": "1992-08-20",
        "time": "06:15",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      }
    }
        """
        return self._request("POST", "/matching/ashtakoot", body=body, secured=True)

    def chart_image(self, body):
        """Chart image (SVG).

        POST /v1/chart/image

        The birth chart (or a divisional chart via `division`, e.g. "D9") drawn as an SVG string in North Indian (`style: "north"`, default) or South Indian (`"south"`) style, plus the houses and their planets as data.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "style": "north",
      "division": "D1"
    }
        """
        return self._request("POST", "/chart/image", body=body, secured=True)

    def ashtakvarga(self, body):
        """Ashtakvarga.

        POST /v1/ashtakvarga

        Bhinna Ashtakvarga points for Sun to Saturn in every sign and house, and the Sarva Ashtakvarga total (337 points). Set `include_contributions` true to see which contributor gave each point.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "include_contributions": false
    }
        """
        return self._request("POST", "/ashtakvarga", body=body, secured=True)

    def dasha_yogini(self, body):
        """Yogini dasha.

        POST /v1/dasha/yogini

        The 36-year Yogini dasha from the birth nakshatra: balance at birth, running chain at `at` (`depth` 1–3, default 2) and the nested timeline (`periods_depth` 0–3, default 1) for about 120 years.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "at": "2026-10-07",
      "depth": 2
    }
        """
        return self._request("POST", "/dasha/yogini", body=body, secured=True)

    def dasha_char(self, body):
        """Jaimini Chara dasha.

        POST /v1/dasha/char

        Sign-based Chara dasha mahadashas from the Lagna (Gary Gomes / K.N. Rao convention, published in the response), with the running period at `at`. Antardashas are not included. `cycles` 1–3 (default 1).

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "at": "2026-10-07"
    }
        """
        return self._request("POST", "/dasha/char", body=body, secured=True)

    def doshas_kalsarpa(self, body):
        """Kaal Sarp dosha.

        POST /v1/doshas/kalsarpa

        Whether all seven planets lie on one side of the Rahu-Ketu axis (full) or all but one (partial), the direction, and the named type from the house of Rahu. Reports the astronomical condition only.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      }
    }
        """
        return self._request("POST", "/doshas/kalsarpa", body=body, secured=True)

    def yogas(self, body):
        """Classical yogas.

        POST /v1/yogas

        Which classical yogas are present in a birth chart: the five Mahapurusha yogas, Gajakesari, Budhaditya, Chandra-Mangala, Sunapha, Anapha, Durudhara, Kemadruma, Vesi, Vosi, Ubhayachari, Adhi, Amala, the three Parivartana types, Harsha, Sarala, Vimala, Guru-Chandala, the Grahana yogas, Shrapit and Angarak, plus clearly labelled variants (counted from the Moon, Jupiter with Ketu). Each yoga lists the exact conditions met, anything that weakens or modifies it, cancellations where they apply (Kemadruma), a fixed description and its source. There is no numeric score. Set include_absent to also list the yogas that were checked and are not formed.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "include_absent": false
    }
        """
        return self._request("POST", "/yogas", body=body, secured=True)

    def varshaphal(self, body):
        """Varshaphal (annual chart).

        POST /v1/varshaphal

        The annual chart for a year: the exact Varsha Pravesh (the instant the Sun returns to its natal sidereal longitude, in UTC and local time), the annual chart for that moment at the birth place or a place you choose, the Muntha (sign, house, lord), the five officers (Panchadhikari) with their positions, and the Mudda dasha for the year. This is Phase A: the year lord is not selected, and the Tri-rashi and Dina-ratri officers are returned as pending because authors differ and the rules await confirmation by an astrologer. The Mudda dasha year length is an input (365.25 or 360 days).

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "year": 2026,
      "location": {
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "mudda_year_days": 365.25
    }
        """
        return self._request("POST", "/varshaphal", body=body, secured=True)

    def muhurta_chaughadiya(self, body):
        """Choghadiya.

        POST /v1/muhurta/chaughadiya

        The eight day and eight night choghadiyas (Udveg, Chal, Labh, Amrit, Kaal, Shubh, Rog) with exact times and their auspicious / neutral / inauspicious nature.

        Example body:
            {
      "date": "2026-10-07",
      "latitude": 19.076,
      "longitude": 72.8777,
      "timezone": "Asia/Kolkata"
    }
        """
        return self._request("POST", "/muhurta/chaughadiya", body=body, secured=True)

    def muhurta_hora(self, body):
        """Hora (planetary hours).

        POST /v1/muhurta/hora

        The 12 day and 12 night planetary hours with the ruling planet and exact times.

        Example body:
            {
      "date": "2026-10-07",
      "latitude": 19.076,
      "longitude": 72.8777,
      "timezone": "Asia/Kolkata"
    }
        """
        return self._request("POST", "/muhurta/hora", body=body, secured=True)

    def biorhythm(self, body):
        """Biorhythm.

        POST /v1/biorhythm

        Physical (23 day), emotional (28 day) and intellectual (33 day) cycle values from -100 to 100 for a date (and up to 62 days) from the birth date.

        Example body:
            {
      "birth_date": "1990-05-15",
      "date": "2026-10-07",
      "days": 7
    }
        """
        return self._request("POST", "/biorhythm", body=body, secured=True)

    def ayanamsha(self, date=None):
        """Ayanamsha value.

        GET /v1/ayanamsha

        The Lahiri ayanamsha for a date (default today).
        """
        return self._request("GET", "/ayanamsha", query={"date": date}, secured=True)

    def reference_planet_nature(self, lang=None):
        """Planet nature table.

        GET /v1/reference/planet-nature

        Classical attributes of the nine planets: nature, element, friends and enemies, exaltation, own signs and more. Free.
        """
        return self._request("GET", "/reference/planet-nature", query={"lang": lang}, secured=True)

    def ai_prediction(self, body):
        """AI prediction.

        POST /v1/ai/prediction

        AI-written prediction for one area of life over a day, week, month or year, in any of 21 languages (en = English, hinglish = Hinglish (Hindi in Roman script), hi = Hindi, mr = Marathi, bn = Bengali, gu = Gujarati, ta = Tamil, te = Telugu, kn = Kannada, ml = Malayalam, pa = Punjabi, or = Odia, ur = Urdu, as = Assamese, ne = Nepali, sa = Sanskrit, kok = Konkani, mai = Maithili, doi = Dogri, sd = Sindhi, ks = Kashmiri). The text is written by OpenAI strictly from facts our engine calculates (returned in facts_used: chart, running dasha, sade sati, transits). Credits depend on the language (English 15, Hindi 25, Odia 55); failed generations are refunded. Not yet available: Bodo, Manipuri (Meitei), Santali. Languages marked beta in /ai/pricing have not yet been reviewed by native speakers. Areas: general, career, finance, marriage, family, education, health. Periods: today, week, month, year.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "language": "hi",
      "area": "career",
      "period": "year"
    }
        """
        return self._request("POST", "/ai/prediction", body=body, secured=True)

    def ai_ask(self, body):
        """AI ask (free-text chat Q&A).

        POST /v1/ai/ask

        Ask any astrology question in free text and get one conversational answer, in any of 21 languages — the same persona, safety and quality rules as the AstroNirnay app's AI chat, but stateless (no account, no chat history stored on our side; optionally pass up to 10 prior turns yourself in `history`). The answer is written by OpenAI strictly from facts our engine calculates (returned in facts_used). Messages detected as self-harm/crisis ideation never reach the model: they get a static support-helpline redirect and are never charged (credits_charged: 0). Credits depend on the language (English 15, Hindi 25, Odia 55); failed generations are refunded.

        Example body:
            {
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "language": "en",
      "question": "Will my career improve in the next few months?"
    }
        """
        return self._request("POST", "/ai/ask", body=body, secured=True)

    def ai_reports(self, body):
        """Create an AI report (PDF).

        POST /v1/ai/reports

        Starts a branded PDF report and returns 202 with a job id. Reports: sade_sati = Sade Sati report, manglik = Manglik report, roadmap_12m = 12-month roadmap, premium_kundali = Premium Personalized Kundali, career_roadmap_5yr = Career 5-Year Roadmap, wealth_roadmap_5yr = Wealth 5-Year Roadmap, love_roadmap_5yr = Love 5-Year Roadmap, marriage_roadmap_5yr = Marriage 5-Year Roadmap, health_roadmap_5yr = Health 5-Year Roadmap, business_roadmap_5yr = Business 5-Year Roadmap. Languages: en, hi, mr, ta, te (more are added after native-speaker review). Credits are charged now (sade_sati 45 in English, manglik 45 in English, roadmap_12m 60 in English, premium_kundali 155 in English, career_roadmap_5yr 40 in English, wealth_roadmap_5yr 40 in English, love_roadmap_5yr 40 in English, marriage_roadmap_5yr 40 in English, health_roadmap_5yr 40 in English, business_roadmap_5yr 40 in English; other languages cost more) and refunded automatically if the report fails. Poll GET /ai/reports/{id} until status is done (typically 30-90 seconds), then download the PDF. The PDF carries the logo and company name you saved under Branding in the dashboard. subject_name is printed on the PDF only and is never sent to the AI. Reports are kept for 30 days. At most 3 reports can be generating at once.

        Example body:
            {
      "report": "sade_sati",
      "language": "hi",
      "birth": {
        "date": "1990-05-15",
        "time": "10:30",
        "latitude": 19.076,
        "longitude": 72.8777,
        "timezone": "Asia/Kolkata"
      },
      "subject_name": "Asha Kumar"
    }
        """
        return self._request("POST", "/ai/reports", body=body, secured=True)

    def ai_reports(self, lang=None):
        """List your recent reports.

        GET /v1/ai/reports

        Your 20 most recent reports with status and download links. Free.
        """
        return self._request("GET", "/ai/reports", query={"lang": lang}, secured=True)

    def ai_reports(self, lang=None):
        """Report status and content.

        GET /v1/ai/reports/{id}

        Status (queued, running, done, failed), progress, and when done the report sections as JSON, the facts used, and the pdf_url. A failed report is refunded (refunded: true). Free.
        """
        return self._request("GET", "/ai/reports/{id}", query={"lang": lang}, secured=True)

    def ai_reports_pdf(self, lang=None):
        """Download the report PDF.

        GET /v1/ai/reports/{id}/pdf

        Returns the branded PDF (application/pdf). 409 until the report is done, 410 after it expires. Send your API key header and save the file on your server. Free.
        """
        return self._request("GET", "/ai/reports/{id}/pdf", query={"lang": lang}, secured=True)

    def ai_pricing(self, lang=None):
        """AI products and credit prices.

        GET /v1/ai/pricing

        Credits per language, quality flag (standard or beta) and the languages that are not available yet. Free.
        """
        return self._request("GET", "/ai/pricing", query={"lang": lang}, secured=True)

    def places_search(self, q, limit=None):
        """Search places.

        GET /v1/places/search

        Find latitude, longitude and time zone for a place name.
        """
        return self._request("GET", "/places/search", query={"q": q, "limit": limit}, secured=True)

    def timezone(self, latitude, longitude, date=None):
        """Time zone for coordinates.

        GET /v1/timezone

        IANA zone and UTC offset for coordinates, optionally as of a date.
        """
        return self._request("GET", "/timezone", query={"latitude": latitude, "longitude": longitude, "date": date}, secured=True)

    def usage(self):
        """Your usage this month.

        GET /v1/usage

        Credit balance, credits and calls used today and this month with a per-endpoint breakdown, and the credit cost of every endpoint. Free: costs no credits.
        """
        return self._request("GET", "/usage", query=None, secured=True)

    def health(self):
        """Service health.

        GET /v1/health

        Public status check; no key required.
        """
        return self._request("GET", "/health", query=None, secured=False)
