import json
import re

import requests
from flask import current_app


VOICE_KEYWORDS = (
    "voice", "voiceover", "voice over", "dubbing", "dub", "audio",
    "recording", "narration", "speech", "interpretation", "interpreting",
)

PROOFREAD_KEYWORDS = ("proofread", "proofreading", "review", "editing", "editor")
MTPE_KEYWORDS = ("mtpe", "machine translation post", "post edit", "post-edit")
SUBTITLE_KEYWORDS = ("subtitle", "subtitling", "caption")
DTP_KEYWORDS = ("dtp", "desktop publishing", "typesetting", "formatting")
CONTENT_KEYWORDS = ("content writing", "copywriting", "copy writing", "writer")
QA_KEYWORDS = ("linguistic qa", "lqa", "quality assurance", "quality check", "qc")
TRANSCRIPTION_KEYWORDS = ("transcription", "transcribe")


def _clean_text(value):
    """Normalize model text so escaped newlines never reach the UI as literal \\n."""
    if value is None:
        return value
    if not isinstance(value, str):
        return value
    text = value.replace("\\r\\n", "\n").replace("\\n", "\n").replace("\\t", "\t")
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    # Avoid excessive blank space while preserving paragraphs.
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def _service_type(service_name):
    name = (service_name or "").strip().lower()
    if any(k in name for k in TRANSCRIPTION_KEYWORDS):
        return "transcription"
    if any(k in name for k in VOICE_KEYWORDS):
        return "voice"
    if any(k in name for k in SUBTITLE_KEYWORDS):
        return "subtitling"
    if any(k in name for k in MTPE_KEYWORDS):
        return "mtpe"
    if any(k in name for k in PROOFREAD_KEYWORDS):
        return "proofreading"
    if any(k in name for k in DTP_KEYWORDS):
        return "dtp"
    if any(k in name for k in CONTENT_KEYWORDS):
        return "content"
    if any(k in name for k in QA_KEYWORDS):
        return "qa"
    return "translation"


def _chat(system_text, user_text, max_completion_tokens=None, json_mode=False):
    api_key = (current_app.config.get("OPENAI_API_KEY") or "").strip()
    if not api_key:
        raise RuntimeError("OPENAI_API_KEY is not configured.")

    api_url = current_app.config.get("OPENAI_API_URL") or "https://api.openai.com/v1/chat/completions"
    model = current_app.config.get("VENDOR_ONBOARDING_OPENAI_MODEL") or current_app.config.get("OPENAI_MODEL") or "gpt-4.1-mini"

    payload = {
        "model": model,
        "messages": [
            {"role": "system", "content": system_text},
            {"role": "user", "content": user_text},
        ],
    }

    # Force machine-readable JSON for generation/scoring calls. Without this,
    # GPT models can occasionally wrap the object in prose/markdown or return
    # an incomplete non-JSON answer even when the prompt requests JSON.
    if json_mode:
        payload["response_format"] = {"type": "json_object"}

    # Keep short qualification-test calls fast on GPT-5 family models.
    if str(model).lower().startswith("gpt-5"):
        payload["reasoning_effort"] = "low"
        if max_completion_tokens:
            payload["max_completion_tokens"] = int(max_completion_tokens)

    response = requests.post(
        api_url,
        headers={"Authorization": "Bearer {}".format(api_key), "Content-Type": "application/json"},
        json=payload,
        timeout=90,
    )
    if response.status_code >= 400:
        raise RuntimeError("OpenAI API error {}: {}".format(response.status_code, response.text[:600]))
    data = response.json()
    choices = data.get("choices") or []
    if not choices:
        raise RuntimeError("OpenAI API returned no response choice.")
    choice = choices[0] or {}
    message = choice.get("message") or {}
    content = message.get("content") or ""
    if not content.strip():
        finish_reason = choice.get("finish_reason") or "unknown"
        raise RuntimeError("OpenAI returned an empty response (finish_reason={}).".format(finish_reason))
    return content


def _test_rules(kind):
    if kind in ("voice", "transcription", "subtitling"):
        return """
This is an AUDIO/VOICE-RELATED assessment.
- Create ONE concise practical task only.
- The audio/recorded/script portion must be designed for 30-50 seconds.
- Use approximately 75-120 spoken words maximum.
- Written instructions must be brief.
- Do not create multiple long exercises.
- Candidate completion time must be 10 minutes or less apart from recording/playback.
"""
    if kind == "proofreading":
        return """
Create a proofreading/editing assessment using ONE intentionally flawed sample of approximately 200-300 words.
Ask the candidate to return a corrected version and optionally list no more than 5 key corrections.
Target completion time: 15-20 minutes.
"""
    if kind == "mtpe":
        return """
Create ONE MTPE assessment using approximately 200-300 words of machine-translated content.
Ask the candidate to post-edit it into publication-ready language and identify no more than 5 important issues.
Target completion time: 15-20 minutes.
"""
    if kind == "dtp":
        return """
Create ONE short practical DTP/formatting scenario with clear requirements and a compact sample.
Do not require external files. Keep all candidate-facing material under 350 words.
Target completion time: 15-20 minutes.
"""
    if kind == "content":
        return """
Create ONE concise writing task. The candidate's expected response should be 250-350 words maximum.
Give a clear audience, tone and objective. Target completion time: 15-20 minutes.
"""
    if kind == "qa":
        return """
Create ONE short linguistic QA sample with planted issues. Keep the sample around 200-300 words.
Ask the candidate to identify/correct the issues and categorize them briefly.
Target completion time: 15-20 minutes.
"""
    return """
Create a TRANSLATION assessment with 2 or at most 3 short sections.
- Total source material should normally be 250-350 words.
- 500 words is an ABSOLUTE ceiling for all candidate-facing test_content, including instructions and source text.
- Prefer one short general/business passage plus one contextual/technical passage; optionally add 5-8 very short UI/terminology strings.
- Do NOT create four or more tasks.
- Do NOT create a full post-editing exercise in addition to several translation passages.
- Target candidate completion time: 15-20 minutes.
"""


def generate_test(service_name, language_pairs=None):
    pairs = ", ".join(language_pairs or []) or "Not language-specific"
    kind = _service_type(service_name)

    system_text = (
        "You design short professional qualification assessments for a language/localization vendor network. "
        "Tests must be fair, practical, concise, and suitable for completion inside a web form. "
        "Never request personal information. Never create an assessment estimated above 20 minutes. "
        "Do not add unnecessary background, repeated instructions, or filler."
    )

    user_text = """Create ONE concise qualification test.
Service: {service}
Language pair(s): {pairs}
Assessment type: {kind}

{rules}

GLOBAL RULES:
- Never state or imply an estimated completion time above 20 minutes.
- Keep instructions short and candidate-friendly.
- Avoid duplicate instructions between instructions and test_content.
- test_content must contain all material/questions the candidate needs.
- Use clear headings such as "Part A", "Part B", etc. where useful.
- Use actual line breaks, never literal \\n sequences.
- maximum_score must be 100.

Return ONLY valid JSON with exactly these keys:
- title
- instructions
- test_content
- rubric
- maximum_score

The rubric should be concise and focus on accuracy, completeness, terminology/style, fluency/quality, and instruction-following as relevant to the service.
""".format(service=service_name, pairs=pairs, kind=kind, rules=_test_rules(kind))

    raw = _chat(system_text, user_text, max_completion_tokens=1400, json_mode=True)
    data = _parse_json(raw)
    data["title"] = _clean_text(data.get("title") or "Qualification Test")
    data["instructions"] = _clean_text(data.get("instructions") or "")
    data["test_content"] = _clean_text(data.get("test_content") or "")
    data["rubric"] = _clean_text(data.get("rubric") or "")
    data["maximum_score"] = 100
    return data


def score_test(service_name, test_content, rubric, answer):
    system_text = (
        "You are a strict but fair professional vendor qualification evaluator. "
        "Score only the submitted work against the provided test and rubric. Keep feedback concise and actionable."
    )
    user_text = """Evaluate this vendor qualification test.
Service: {service}
TEST:
{test}

RUBRIC:
{rubric}

CANDIDATE ANSWER:
{answer}

Return ONLY valid JSON with keys:
- score (number 0-100)
- feedback (concise professional feedback)
- strengths (array of strings)
- improvements (array of strings)
""".format(service=service_name, test=test_content, rubric=rubric, answer=answer)
    raw = _chat(system_text, user_text, max_completion_tokens=1400, json_mode=True)
    data = _parse_json(raw)
    data["feedback"] = _clean_text(data.get("feedback") or "")
    return data


def _parse_json(raw):
    raw = (raw or "").strip()
    if not raw:
        raise RuntimeError("AI returned an empty response.")

    # Be tolerant of fenced JSON if a provider/model ignores response_format.
    raw = re.sub(r"^```(?:json)?\s*", "", raw, flags=re.I)
    raw = re.sub(r"\s*```$", "", raw)
    raw = raw.strip()

    try:
        data = json.loads(raw)
        if isinstance(data, dict):
            return data
    except Exception:
        pass

    # Fallback for providers that prepend/append a small amount of prose.
    start = raw.find("{")
    end = raw.rfind("}")
    if start >= 0 and end > start:
        candidate = raw[start:end + 1]
        try:
            data = json.loads(candidate)
            if isinstance(data, dict):
                return data
        except Exception:
            pass

    excerpt = re.sub(r"\s+", " ", raw)[:240]
    raise RuntimeError("AI response was not valid JSON. Response excerpt: {}".format(excerpt))
