import json
import logging
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

from fastapi import HTTPException
from database import get_connection
from stored_jd_pdf import create_jd_pdf


HRMS_JOBS_URL = "https://api-hrms.kineticcosmos.in/public/careers/jobs"

logger = logging.getLogger("careers.hrms_sync")


# ============================================================
# FETCH AND VALIDATE PUBLISHED HRMS JOBS
# ============================================================

def fetch_published_jobs():
    try:
        request = Request(
            HRMS_JOBS_URL,
            headers={
                "Accept": "application/json",
                "User-Agent": "KineticCosmos-Careers/1.0",
            },
            method="GET",
        )

        with urlopen(request, timeout=20) as response:
            status_code = response.status
            response_body = response.read().decode("utf-8")

        logger.info(
            "HRMS jobs API response: status=%s, url=%s",
            status_code,
            HRMS_JOBS_URL,
        )

        try:
            jobs = json.loads(response_body)
        except json.JSONDecodeError as exc:
            logger.error(
                "HRMS returned invalid JSON. Response preview: %s",
                response_body[:2000],
            )
            raise ValueError("HRMS returned invalid JSON") from exc

        if not isinstance(jobs, list):
            logger.error(
                "Expected jobs array from HRMS. Received type=%s, body=%s",
                type(jobs).__name__,
                response_body[:2000],
            )
            raise ValueError("Expected a jobs array")

        seen = set()

        for index, job in enumerate(jobs):
            if not isinstance(job, dict):
                raise ValueError(
                    f"Invalid job object at index {index}"
                )

            job_id = job.get("id")

            if type(job_id) is not int or job_id <= 0:
                raise ValueError(
                    f"Invalid HRMS job ID at index {index}"
                )

            if job_id in seen:
                raise ValueError(
                    f"Duplicate HRMS job ID: {job_id}"
                )

            seen.add(job_id)

            if (
                not isinstance(job.get("job_title"), str)
                or not job["job_title"].strip()
            ):
                raise ValueError(
                    f"Missing job title for HRMS job ID {job_id}"
                )

            string_fields = (
                "department",
                "summary",
                "experience",
                "work_mode",
                "location",
                "salary",
                "employment_type",
                "education",
                "certifications",
                "shift_timing",
                "other",
                "pdf_url",
            )

            for field in string_fields:
                value = job.get(field)

                if value is not None and not isinstance(value, str):
                    raise ValueError(
                        f"Invalid field '{field}' for HRMS job ID {job_id}"
                    )

            for field in ("skills", "responsibilities"):
                value = job.get(field)

                if value is None:
                    job[field] = []

                elif isinstance(value, str):
                    try:
                        job[field] = json.loads(value)
                    except json.JSONDecodeError as exc:
                        raise ValueError(
                            f"Invalid JSON in '{field}' for HRMS job ID {job_id}"
                        ) from exc

                if not isinstance(job[field], list):
                    raise ValueError(
                        f"'{field}' must be an array for HRMS job ID {job_id}"
                    )

                if any(not isinstance(item, str) for item in job[field]):
                    raise ValueError(
                        f"'{field}' contains a non-string value "
                        f"for HRMS job ID {job_id}"
                    )

        logger.info(
            "Successfully fetched and validated %s published HRMS jobs",
            len(jobs),
        )

        return jobs

    except HTTPError as exc:
        # Important: print the upstream HTTP 500 response body.
        try:
            error_body = exc.read().decode("utf-8", errors="replace")
        except Exception:
            error_body = "Unable to read HRMS error response"

        logger.error(
            "HRMS jobs API failed: status=%s, reason=%s, url=%s, response=%s",
            exc.code,
            exc.reason,
            HRMS_JOBS_URL,
            error_body[:4000],
        )

        raise HTTPException(
            status_code=503,
            detail="Current openings are temporarily unavailable. Please try again.",
        ) from exc

    except URLError as exc:
        logger.error(
            "Unable to connect to HRMS jobs API: url=%s, reason=%s",
            HRMS_JOBS_URL,
            exc.reason,
        )

        raise HTTPException(
            status_code=503,
            detail="Unable to connect to the careers service. Please try again.",
        ) from exc

    except HTTPException:
        raise

    except Exception as exc:
        logger.exception(
            "Failed to fetch or validate HRMS jobs. URL=%s, error=%s",
            HRMS_JOBS_URL,
            str(exc),
        )

        raise HTTPException(
            status_code=503,
            detail="Current openings are temporarily unavailable. Please try again.",
        ) from exc


# ============================================================
# BUILD JOB DESCRIPTION
# ============================================================

def job_description(job):
    """
    Public careers page par sirf summary show hogi.
    Skills, responsibilities, education, certifications,
    shift_timing aur other description mein combine nahi honge.
    """
    return (job.get("summary") or "").strip()

# ============================================================
# SYNC HRMS JOBS INTO KINETIC COSMOS DATABASE
# ============================================================

def sync_hrms_jobs():
    conn = None
    cursor = None
    lock_acquired = False

    try:
        conn = get_connection()

        if conn is None:
            raise RuntimeError("Database connection returned None")

        cursor = conn.cursor()

        # Prevent overlapping synchronization requests.
        cursor.execute(
            "SELECT GET_LOCK('kinetic_careers_hrms_sync', 12)"
        )

        locked = cursor.fetchone()

        if not locked or locked[0] != 1:
            raise HTTPException(
                status_code=503,
                detail="Openings are refreshing. Please retry.",
            )

        lock_acquired = True

        # Fetch all jobs before changing database rows.
        jobs = fetch_published_jobs()

        logger.info(
            "Starting HRMS job sync. Jobs received: %s",
            len(jobs),
        )

        for job in jobs:
            job_id = job["id"]

            try:
                description = job_description(job)

                jd_filename = (
                    create_jd_pdf(job, description)
                    if job.get("pdf_url")
                    else None
                )

                cursor.execute(
                    """
                    INSERT INTO job (
                        hrms_jd_id,
                        title,
                        department,
                        description,
                        experience,
                        work_mode,
                        location,
                        salary,
                        vacancies,
                        employment_type,
                        skills,
                        jd_file,
                        status
                    )
                    VALUES (
                        %s, %s, %s, %s, %s, %s, %s,
                        %s, 1, %s, %s, %s, 'active'
                    )
                    ON DUPLICATE KEY UPDATE
                        title = VALUES(title),
                        department = VALUES(department),
                        description = VALUES(description),
                        experience = VALUES(experience),
                        work_mode = VALUES(work_mode),
                        location = VALUES(location),
                        salary = VALUES(salary),
                        employment_type = VALUES(employment_type),
                        skills = VALUES(skills),
                        jd_file = VALUES(jd_file),
                        status = 'active'
                    """,
                    (
                        job_id,
                        job["job_title"],
                        job.get("department") or "",
                        description,
                        job.get("experience") or "",
                        job.get("work_mode") or "",
                        job.get("location") or "",
                        job.get("salary") or "",
                        job.get("employment_type") or "",
                        ", ".join(job["skills"]),
                        jd_filename,
                    ),
                )

            except Exception:
                logger.exception(
                    "Failed to sync HRMS job ID=%s, title=%s",
                    job_id,
                    job.get("job_title"),
                )
                raise

        # Close previously imported jobs no longer published in HRMS.
        ids = [job["id"] for job in jobs]

        if ids:
            placeholders = ",".join(["%s"] * len(ids))

            cursor.execute(
                """
                UPDATE job
                SET status = 'closed'
                WHERE hrms_jd_id IS NOT NULL
                  AND hrms_jd_id NOT IN (
                """ + placeholders + ")",
                tuple(ids),
            )
        else:
            cursor.execute(
                """
                UPDATE job
                SET status = 'closed'
                WHERE hrms_jd_id IS NOT NULL
                """
            )

        conn.commit()

        logger.info(
            "HRMS job sync completed successfully. Total jobs: %s",
            len(jobs),
        )

    except Exception:
        if conn is not None:
            try:
                conn.rollback()
            except Exception:
                logger.exception("Database rollback failed")

        logger.exception("HRMS JOB SYNC ERROR")
        raise

    finally:
        if cursor is not None:
            if lock_acquired:
                try:
                    cursor.execute(
                        "SELECT RELEASE_LOCK('kinetic_careers_hrms_sync')"
                    )
                    cursor.fetchone()
                except Exception:
                    logger.exception("Failed to release HRMS sync lock")

            try:
                cursor.close()
            except Exception:
                logger.exception("Failed to close database cursor")

        if conn is not None:
            try:
                conn.close()
            except Exception:
                logger.exception("Failed to close database connection")