"""AI job description drafting, rewrite, validation, and unified Create Job."""

from __future__ import annotations

from typing import Any
from uuid import uuid4

from fastapi import HTTPException, status

from app.prompts import Persona, render_jd_draft_prompts
from app.schemas.bias_detection import BiasDetectionRequest
from app.schemas.common import JobStatus
from app.schemas.helpers import JdInclusivityRewriteRequest
from app.schemas.job_descriptions import (
    EmploymentType,
    ExperienceRange,
    JobAction,
    JobCreateBody,
    JobCreateResponse,
    JobDescriptionDraftRequest,
    JobDescriptionDraftResponse,
    JobDescriptionSections,
    JobDescriptionValidateRequest,
    JobDescriptionValidateResponse,
    JobDescriptionValidationIssue,
    JobDescriptionValidationResult,
    JobDraftBody,
    JobPublishBody,
    JobRewriteBody,
    JobValidateBody,
)
from app.services.analysis.bias import BiasDetectionService
from app.services.screening.job_store import get_job, save_job
from app.services.shared.ai_generate import generate_json
from app.services.shared.helpers import JdInclusivityService


def _sections_from_raw(raw: Any) -> JobDescriptionSections:
    if not isinstance(raw, dict):
        raw = {}
    nice = list(raw.get("nice_to_have") or raw.get("preferred_skills") or [])
    preferred = list(raw.get("preferred_skills") or nice)
    return JobDescriptionSections(
        summary=raw.get("summary"),
        responsibilities=list(raw.get("responsibilities") or []),
        requirements=list(raw.get("requirements") or []),
        nice_to_have=nice,
        preferred_skills=preferred,
        benefits=list(raw.get("benefits") or []),
    )


def _markdown_from_sections(role_title: str, sections: JobDescriptionSections) -> str:
    parts = [f"# {role_title}", ""]
    if sections.summary:
        parts.extend([sections.summary, ""])
    if sections.responsibilities:
        parts.append("## Responsibilities")
        parts.extend(f"- {r}" for r in sections.responsibilities)
        parts.append("")
    if sections.requirements:
        parts.append("## Required qualifications")
        parts.extend(f"- {r}" for r in sections.requirements)
        parts.append("")
    preferred = sections.preferred_skills or sections.nice_to_have
    if preferred:
        parts.append("## Preferred skills")
        parts.extend(f"- {r}" for r in preferred)
        parts.append("")
    if sections.benefits:
        parts.append("## Benefits")
        parts.extend(f"- {r}" for r in sections.benefits)
        parts.append("")
    return "\n".join(parts).strip() + "\n"


def _yoe_label(value: ExperienceRange | str | None) -> str:
    if value is None:
        return ""
    if isinstance(value, ExperienceRange):
        return f"{value.value} years"
    return str(value)


def _ensure_correlation_id(value: Any) -> Any:
    return value if value is not None else uuid4()


class JobDescriptionsService:
    def __init__(self) -> None:
        self._inclusivity = JdInclusivityService()
        self._bias = BiasDetectionService()

    async def draft(
        self,
        payload: JobDescriptionDraftRequest,
        *,
        company_id: str | None = None,
        created_by: str | None = None,
    ) -> JobDescriptionDraftResponse:
        correlation_id = _ensure_correlation_id(payload.correlation_id)
        resolved_company = company_id or payload.company_id
        yoe = _yoe_label(payload.years_of_experience)
        system, user = render_jd_draft_prompts(
            persona=payload.persona,
            role_title=payload.role_title,
            seniority=payload.seniority or "",
            department=payload.department or "",
            employment_type=payload.employment_type.value,
            location=payload.location or "",
            years_of_experience=yoe,
            skills=payload.skills,
            responsibilities=payload.responsibilities,
            company_context=payload.company_context or "",
            tone_notes=payload.tone_notes or "",
            language=payload.language,
            salary_range=payload.salary_range or "",
            currency=payload.currency or "",
            openings=str(payload.openings) if payload.openings is not None else "",
        )
        system += (
            "\nReturn JSON: {\"markdown\",\"sections\":"
            "{\"summary\",\"responsibilities\":[],\"requirements\":[],"
            "\"nice_to_have\":[],\"preferred_skills\":[],\"benefits\":[]}}"
        )

        def local() -> dict:
            skills = payload.skills or ["relevant domain skills"]
            exp = yoe or payload.seniority or "relevant"
            resp = payload.responsibilities or [
                f"Own delivery for the {payload.role_title} function",
                "Collaborate with cross-functional partners",
                "Improve processes and measurable outcomes",
            ]
            reqs = [f"Proven experience with {s}" for s in skills]
            reqs.append(f"Approximately {exp} of relevant experience")
            if payload.location:
                reqs.append(f"Able to work from {payload.location}")
            benefits = [
                "Growth and learning opportunities",
                "Inclusive and collaborative culture",
            ]
            if payload.salary_range:
                pay = payload.salary_range
                if payload.currency:
                    pay = f"{payload.currency} {pay}"
                benefits.insert(0, f"Compensation range: {pay}")
            else:
                benefits.insert(0, "Competitive compensation")
            openings_bit = (
                f" ({payload.openings} opening{'s' if payload.openings != 1 else ''})"
                if payload.openings
                else ""
            )
            summary = (
                f"We are hiring a {payload.role_title}{openings_bit} "
                f"({payload.employment_type.value.replace('_', ' ')})"
                f"{' in ' + payload.department if payload.department else ''}"
                f"{' — ' + payload.location if payload.location else ''}."
            )
            sections = {
                "summary": summary,
                "responsibilities": resp,
                "requirements": reqs,
                "nice_to_have": [],
                "preferred_skills": [],
                "benefits": benefits,
            }
            return {
                "markdown": _markdown_from_sections(
                    payload.role_title, _sections_from_raw(sections)
                ),
                "sections": sections,
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        sections = _sections_from_raw(data.get("sections") or {})
        markdown = data.get("markdown") or _markdown_from_sections(
            payload.role_title, sections
        )

        validation = await self._validate_content(
            role_title=payload.role_title,
            markdown=markdown,
            sections=sections,
            skills=payload.skills,
            language=payload.language,
        )

        row = save_job(
            job_id=payload.job_id,
            status="draft",
            role_title=payload.role_title,
            title=payload.role_title,
            markdown=markdown,
            sections=sections.model_dump(),
            validation=validation.model_dump(),
            company_id=resolved_company,
            created_by=created_by,
            employment_type=payload.employment_type.value,
            location=payload.location,
            years_of_experience=payload.years_of_experience.value
            if payload.years_of_experience
            else None,
            seniority=payload.seniority,
            department=payload.department,
            meta={
                "persona": payload.persona.value,
                "provider": provider,
                "salary_range": payload.salary_range,
                "currency": payload.currency,
                "openings": payload.openings,
            },
        )

        return JobDescriptionDraftResponse(
            correlation_id=correlation_id,
            job_id=row.job_id,
            role_title=payload.role_title,
            persona=payload.persona,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Drafted JD via {provider}",
            prompt_preview={"system": system, "user": user},
            markdown=markdown,
            sections=sections,
            validation=validation,
            salary_range=payload.salary_range,
            currency=payload.currency,
            openings=payload.openings,
        )

    async def validate(
        self, payload: JobDescriptionValidateRequest
    ) -> JobDescriptionValidateResponse:
        correlation_id = _ensure_correlation_id(payload.correlation_id)
        markdown = (payload.job_description or "").strip()
        role_title = payload.role_title
        sections = JobDescriptionSections()
        if not markdown and payload.job_id:
            stored = get_job(payload.job_id)
            if stored is None:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail=f"job_id not found: {payload.job_id}",
                )
            markdown = (stored.markdown or "").strip()
            sections = _sections_from_raw(stored.sections or {})
            role_title = role_title or stored.role_title
        if not markdown:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Provide job_description and/or a valid job_id",
            )
        validation = await self._validate_content(
            role_title=role_title,
            markdown=markdown,
            sections=sections,
            skills=payload.skills,
            language=payload.language,
        )
        return JobDescriptionValidateResponse(
            correlation_id=correlation_id,
            role_title=role_title,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message="JD validation complete",
            validation=validation,
        )

    async def _validate_content(
        self,
        *,
        role_title: str | None,
        markdown: str,
        sections: JobDescriptionSections,
        skills: list[str],
        language: str,
    ) -> JobDescriptionValidationResult:
        issues: list[JobDescriptionValidationIssue] = []
        missing: list[str] = []
        text = markdown or ""
        lower = text.lower()

        def _empty_list(vals: list[str]) -> bool:
            return not any(str(v).strip() for v in vals)

        if not (sections.summary or "").strip() and "responsibilities" not in lower:
            if len(text) < 80:
                missing.append("summary")
                issues.append(
                    JobDescriptionValidationIssue(
                        code="missing_summary",
                        severity="high",
                        field="summary",
                        message="Job summary is missing or too short",
                        suggestion="Add a 2–4 sentence overview of the role",
                    )
                )
        if _empty_list(sections.responsibilities) and "## responsibilities" not in lower:
            missing.append("responsibilities")
            issues.append(
                JobDescriptionValidationIssue(
                    code="missing_responsibilities",
                    severity="high",
                    field="responsibilities",
                    message="No clear responsibilities section",
                    suggestion="List 4–8 actionable responsibility bullets",
                )
            )
        if (
            _empty_list(sections.requirements)
            and "qualif" not in lower
            and "requirement" not in lower
        ):
            missing.append("requirements")
            issues.append(
                JobDescriptionValidationIssue(
                    code="missing_qualifications",
                    severity="high",
                    field="requirements",
                    message="Required qualifications are missing",
                    suggestion="Add required skills, experience, and qualifications",
                )
            )
        preferred = sections.preferred_skills or sections.nice_to_have
        if _empty_list(preferred) and "preferred" not in lower and "nice" not in lower:
            missing.append("preferred_skills")
            issues.append(
                JobDescriptionValidationIssue(
                    code="missing_preferred_skills",
                    severity="low",
                    field="preferred_skills",
                    message="Preferred / nice-to-have skills not listed",
                    suggestion="Add optional skills to broaden the candidate pool",
                )
            )
        if _empty_list(sections.benefits) and "benefit" not in lower:
            missing.append("benefits")
            issues.append(
                JobDescriptionValidationIssue(
                    code="missing_benefits",
                    severity="medium",
                    field="benefits",
                    message="Benefits section is missing",
                    suggestion="Include compensation, growth, or culture benefits",
                )
            )

        clarity = 0.9
        professionalism = 0.9
        if text.count("!") > 3:
            clarity -= 0.1
            issues.append(
                JobDescriptionValidationIssue(
                    code="tone_exclamation",
                    severity="low",
                    field="job_description",
                    message="Excessive exclamation marks may reduce professionalism",
                )
            )
        buzz = ["rockstar", "ninja", "guru", "crush it", "work hard play hard"]
        for b in buzz:
            if b in lower:
                professionalism -= 0.15
                issues.append(
                    JobDescriptionValidationIssue(
                        code="unprofessional_phrase",
                        severity="medium",
                        field="job_description",
                        message=f"Unprofessional or vague phrase: '{b}'",
                        suggestion="Use concrete skills and outcomes instead",
                    )
                )

        relevance = 1.0
        if skills:
            hits = sum(1 for s in skills if s.lower() in lower)
            relevance = hits / max(1, len(skills))
            if relevance < 0.5:
                issues.append(
                    JobDescriptionValidationIssue(
                        code="skills_not_reflected",
                        severity="medium",
                        field="skills",
                        message="Several skills are not reflected in the JD text",
                        suggestion="Mention required skills in requirements or summary",
                    )
                )

        bias_flags: list[dict[str, Any]] = []
        bias_risk = 0.0
        try:
            bias_resp = await self._bias.analyze(
                BiasDetectionRequest(
                    content_type="job_description",
                    content=text,
                    job_description=text,
                    language=language,
                )
            )
            bias_risk = float(bias_resp.risk_score or 0.0)
            bias_flags = [f.model_dump() for f in (bias_resp.flags or [])]
            for flag in bias_resp.flags or []:
                issues.append(
                    JobDescriptionValidationIssue(
                        code=f"bias_{flag.category}",
                        severity=flag.severity or "medium",
                        field="job_description",
                        message=flag.description,
                        suggestion=flag.recommendation,
                    )
                )
        except Exception:  # noqa: BLE001
            pass

        completeness = max(0.0, 1.0 - (len(missing) * 0.18))
        passed = (
            completeness >= 0.7
            and bias_risk < 0.6
            and not any(
                i.severity == "high" and i.code.startswith("missing_") for i in issues
            )
        )
        return JobDescriptionValidationResult(
            passed=passed,
            completeness_score=round(completeness, 3),
            clarity_score=round(max(0.0, clarity), 3),
            relevance_score=round(relevance, 3),
            professionalism_score=round(max(0.0, professionalism), 3),
            bias_risk_score=round(bias_risk, 3),
            missing_sections=missing,
            issues=issues,
            bias_flags=bias_flags,
        )

    async def create_job(
        self,
        action: JobAction,
        payload: JobCreateBody,
        *,
        company_id: str | None = None,
        created_by: str | None = None,
    ) -> JobCreateResponse:
        """Unified Create Job: draft | rewrite | validate | publish (?action=)."""
        correlation_id = _ensure_correlation_id(payload.correlation_id)
        resolved_company = company_id or getattr(payload, "company_id", None)

        if action == JobAction.DRAFT:
            assert isinstance(payload, JobDraftBody)
            draft_req = JobDescriptionDraftRequest(
                correlation_id=correlation_id,
                role_title=payload.role_title,
                persona=payload.persona or Persona.HR_BEHAVIORAL,
                seniority=payload.seniority,
                department=payload.department,
                employment_type=payload.employment_type or EmploymentType.FULL_TIME,
                location=payload.location,
                years_of_experience=payload.years_of_experience,
                skills=payload.skills,
                responsibilities=payload.responsibilities,
                company_context=payload.company_context,
                salary_range=payload.salary_range,
                currency=payload.currency,
                openings=payload.openings,
                company_id=resolved_company,
                job_id=payload.job_id,
                tone_notes=payload.tone_notes,
                language=payload.language,
                options=payload.options,
            )
            drafted = await self.draft(
                draft_req, company_id=resolved_company, created_by=created_by
            )
            return JobCreateResponse(
                correlation_id=drafted.correlation_id,
                action=JobAction.DRAFT,
                job_id=drafted.job_id,
                status_label="draft",
                role_title=drafted.role_title,
                persona=drafted.persona,
                markdown=drafted.markdown,
                sections=drafted.sections,
                validation=drafted.validation,
                prompt_preview=drafted.prompt_preview,
                status=drafted.status,
                stub=drafted.stub,
                message=drafted.message,
                salary_range=drafted.salary_range,
                currency=drafted.currency,
                openings=drafted.openings,
            )

        if action == JobAction.REWRITE:
            assert isinstance(payload, JobRewriteBody)
            jd_text = (payload.job_description or "").strip()
            if not jd_text and payload.job_id:
                stored = get_job(payload.job_id)
                if stored is None:
                    raise HTTPException(
                        status_code=status.HTTP_404_NOT_FOUND,
                        detail=f"job_id not found: {payload.job_id}",
                    )
                jd_text = (stored.markdown or "").strip()
                role_title = payload.role_title or stored.role_title
            else:
                role_title = payload.role_title
            if len(jd_text) < 20:
                raise HTTPException(
                    status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                    detail="job_description (min 20 chars) or job_id is required for action=rewrite",
                )
            rewritten = await self._inclusivity.rewrite(
                JdInclusivityRewriteRequest(
                    correlation_id=correlation_id,
                    job_description=jd_text,
                    role_title=role_title,
                    language=payload.language,
                    options=payload.options,
                )
            )
            sections = JobDescriptionSections()
            validation = await self._validate_content(
                role_title=role_title,
                markdown=rewritten.rewritten_markdown or jd_text,
                sections=sections,
                skills=payload.skills,
                language=payload.language,
            )
            row = None
            if payload.job_id or role_title:
                row = save_job(
                    job_id=payload.job_id,
                    status="draft",
                    role_title=role_title or "Role",
                    title=role_title,
                    markdown=rewritten.rewritten_markdown,
                    sections=sections.model_dump(),
                    validation=validation.model_dump(),
                    company_id=resolved_company,
                    created_by=created_by,
                    employment_type=(
                        payload.employment_type or EmploymentType.FULL_TIME
                    ).value,
                    location=payload.location,
                    years_of_experience=payload.years_of_experience.value
                    if payload.years_of_experience
                    else None,
                    seniority=payload.seniority,
                    department=payload.department,
                    meta={"action": "rewrite"},
                )
            return JobCreateResponse(
                correlation_id=correlation_id,
                action=JobAction.REWRITE,
                job_id=row.job_id if row else payload.job_id,
                status_label="draft",
                role_title=role_title,
                markdown=rewritten.rewritten_markdown,
                sections=sections,
                removed_bias_phrases=rewritten.removed_bias_phrases,
                notes=rewritten.notes,
                validation=validation,
                status=rewritten.status,
                stub=rewritten.stub,
                message=rewritten.message,
            )

        if action == JobAction.VALIDATE:
            assert isinstance(payload, JobValidateBody)
            vreq = JobDescriptionValidateRequest(
                correlation_id=correlation_id,
                role_title=payload.role_title,
                job_description=payload.job_description,
                job_id=payload.job_id,
                skills=payload.skills,
                language=payload.language,
                options=payload.options,
            )
            validated = await self.validate(vreq)
            markdown = (payload.job_description or "").strip()
            sections = JobDescriptionSections()
            if payload.job_id:
                stored = get_job(payload.job_id)
                if stored:
                    markdown = markdown or (stored.markdown or "")
                    sections = _sections_from_raw(stored.sections or {})
                    save_job(
                        job_id=payload.job_id,
                        status="validated"
                        if validated.validation.passed
                        else stored.status,
                        role_title=stored.role_title,
                        title=stored.title or stored.role_title,
                        markdown=stored.markdown,
                        sections=stored.sections or {},
                        validation=validated.validation.model_dump(),
                        company_id=stored.company_id or resolved_company,
                        created_by=stored.created_by or created_by,
                        platform_job_id=stored.platform_job_id,
                        employment_type=stored.employment_type,
                        location=stored.location,
                        years_of_experience=stored.years_of_experience,
                        seniority=stored.seniority,
                        department=stored.department,
                        meta=stored.meta or {},
                    )
            return JobCreateResponse(
                correlation_id=validated.correlation_id,
                action=JobAction.VALIDATE,
                job_id=payload.job_id,
                status_label="validated" if validated.validation.passed else "draft",
                role_title=validated.role_title,
                markdown=markdown or None,
                sections=sections,
                validation=validated.validation,
                status=validated.status,
                stub=validated.stub,
                message=validated.message,
            )

        if action == JobAction.PUBLISH:
            assert isinstance(payload, JobPublishBody)
            stored = get_job(payload.job_id)
            if stored is None:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail=f"job_id not found: {payload.job_id}",
                )
            sections = _sections_from_raw(stored.sections or {})
            validation = await self._validate_content(
                role_title=stored.role_title,
                markdown=stored.markdown or "",
                sections=sections,
                skills=payload.skills,
                language=payload.language,
            )
            if not validation.passed and not payload.options.get("force_publish"):
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail={
                        "message": (
                            "JD failed validation; fix issues or pass "
                            "options.force_publish=true"
                        ),
                        "validation": validation.model_dump(),
                    },
                )
            # platform_job_id is owned by Platform integration (options only)
            platform_job_id = (
                payload.options.get("platform_job_id")
                if isinstance(payload.options, dict)
                else None
            ) or stored.platform_job_id
            row = save_job(
                job_id=stored.job_id,
                status="published",
                role_title=stored.role_title,
                title=stored.title or stored.role_title,
                markdown=stored.markdown,
                sections=stored.sections or {},
                validation=validation.model_dump(),
                company_id=resolved_company or stored.company_id,
                created_by=created_by or stored.created_by,
                platform_job_id=platform_job_id,
                employment_type=stored.employment_type,
                location=payload.location or stored.location,
                years_of_experience=(
                    payload.years_of_experience.value
                    if payload.years_of_experience
                    else stored.years_of_experience
                ),
                seniority=payload.seniority or stored.seniority,
                department=payload.department or stored.department,
                meta={**(stored.meta or {}), "published": True},
            )
            return JobCreateResponse(
                correlation_id=correlation_id,
                action=JobAction.PUBLISH,
                job_id=row.job_id,
                platform_job_id=row.platform_job_id,
                status_label="published",
                role_title=row.role_title,
                markdown=row.markdown,
                sections=_sections_from_raw(row.sections or {}),
                validation=validation,
                status=JobStatus.SUCCEEDED,
                stub=False,
                message=(
                    "Job AI payload published in gateway. "
                    "Platform links marketplace Job ids via integration "
                    "(options.platform_job_id)."
                ),
            )

        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"Unsupported action: {action}",
        )
