# ruff: noqa: E402

"""
GenAI/LLM Clinical Documentation Assistant - Non-instrumented Version

A baseline implementation without MCA SDK instrumentation for comparison.
"""

import logging
import os
import sys
import time
import random

# Configure logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Add both sdk-examples (for shared.py) and mca-prototype root (for mca_sdk) to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from shared import (
    print_gcp_auth_status,
    print_collector_status,
)


def estimate_openai_cost(model: str, prompt_tokens: int, completion_tokens: int) -> float:
    """Estimate OpenAI API cost based on token usage."""
    # Simplified cost estimation
    if "gpt-4" in model:
        cost_per_prompt_token = 0.00003
        cost_per_completion_token = 0.00006
    else:
        cost_per_prompt_token = 0.0000015
        cost_per_completion_token = 0.000002

    return (prompt_tokens * cost_per_prompt_token) + (completion_tokens * cost_per_completion_token)


# ==========================================
# Mock Clinical Data
# ==========================================

MOCK_ENCOUNTERS = [
    """Patient presents with fever (101.5°F), productive cough with yellow sputum, and body aches for 3 days.
    No recent travel history. Previously vaccinated for influenza this season.
    Lungs clear to auscultation bilaterally. No wheezing or rales noted.""",
    """72-year-old male with history of hypertension presents for routine follow-up.
    Blood pressure 142/88 mmHg. Currently on lisinopril 10mg daily.
    Reports good medication compliance. No chest pain, shortness of breath, or edema.
    No new symptoms since last visit.""",
    """45-year-old female with Type 2 Diabetes Mellitus, HbA1c 8.2% (last check 3 months ago).
    Reports difficulty with dietary adherence due to work schedule.
    No hypoglycemic episodes. Currently on metformin 1000mg twice daily.
    Denies polyuria, polydipsia, or unexplained weight loss.""",
    """28-year-old female, 8 weeks pregnant, presents for initial prenatal visit.
    Last menstrual period 8 weeks ago. Positive home pregnancy test.
    Mild nausea in mornings, no vomiting. Taking prenatal vitamins.
    No vaginal bleeding or cramping. No significant medical history.""",
]

MOCK_SUMMARIES = [
    "Clinical Summary: Patient with acute upper respiratory infection, likely viral etiology given symptom duration and clear lung exam. Recommend symptomatic treatment, hydration, rest. Consider rapid flu test if symptoms worsen. Return if fever persists >5 days or develops dyspnea.",
    "Clinical Summary: Hypertension management visit. Blood pressure slightly elevated at 142/88 despite current medication. Consider increasing lisinopril to 20mg daily or adding second agent. Patient compliant with medications. Schedule follow-up in 4 weeks to reassess BP control.",
    "Clinical Summary: Type 2 Diabetes with suboptimal glycemic control (HbA1c 8.2%). Dietary non-compliance identified as primary factor. Recommend nutrition counseling and diabetes education. Consider medication adjustment if HbA1c remains elevated at 3-month follow-up. Monitor for diabetic complications.",
    "Clinical Summary: Initial prenatal visit at 8 weeks gestation. Patient experiencing normal early pregnancy symptoms. Recommend continue prenatal vitamins with folic acid. Schedule comprehensive prenatal panel: CBC, blood type, antibody screen, rubella, HIV, hepatitis B, urinalysis. Next visit at 12 weeks for first trimester ultrasound.",
]


def summarize_clinical_note(encounter_note: str) -> dict:
    """
    Generate clinical summary using simulated LLM mode.

    Args:
        encounter_note: Raw clinical encounter text

    Returns:
        dict with summary, token counts, cost, and latency
    """
    start_time = time.time()

    try:
        # Mock response structure matching OpenAI format
        mock_prompt_tokens = len(encounter_note.split()) * 1.3  # Rough estimate
        mock_completion_tokens = random.randint(60, 120)  # Typical summary length

        # Pick a random mock summary that corresponds to this encounter
        encounter_index = (
            MOCK_ENCOUNTERS.index(encounter_note) if encounter_note in MOCK_ENCOUNTERS else 0
        )
        mock_content = MOCK_SUMMARIES[encounter_index]

        response = {
            "choices": [{"message": {"role": "assistant", "content": mock_content}}],
            "usage": {
                "prompt_tokens": int(mock_prompt_tokens),
                "completion_tokens": mock_completion_tokens,
                "total_tokens": int(mock_prompt_tokens) + mock_completion_tokens,
            },
            "model": "gpt-3.5-turbo-mock",
        }

        time.sleep(random.uniform(0.1, 0.4))

        # Calculate latency
        latency = time.time() - start_time

        # Extract token counts
        prompt_tokens = response["usage"]["prompt_tokens"]
        completion_tokens = response["usage"]["completion_tokens"]
        total_tokens = response["usage"]["total_tokens"]
        model_name = response["model"]

        # Calculate cost using helper
        total_cost = estimate_openai_cost(model_name, prompt_tokens, completion_tokens)

        # Log completion
        logger.info(
            f"LLM completion: model={model_name}, prompt_tokens={prompt_tokens}, "
            f"completion_tokens={completion_tokens}, latency={latency:.3f}s, status=success"
        )
        logger.info(f"Notes processed: 1 (model={model_name})")

        return {
            "summary": response["choices"][0]["message"]["content"],
            "model": model_name,
            "prompt_tokens": prompt_tokens,
            "completion_tokens": completion_tokens,
            "total_tokens": total_tokens,
            "cost_usd": total_cost,
            "latency_seconds": latency,
        }

    except Exception as e:
        logger.error(f"Error during completion: {e}")
        latency = time.time() - start_time
        logger.error(
            f"LLM completion error: model=gpt-3.5-turbo, latency={latency:.3f}s, status=error"
        )
        raise


def main():
    logger.info("GenAI Clinical Documentation Assistant - Non-instrumented Version")

    # Verify prerequisites
    if not print_gcp_auth_status() or not print_collector_status():
        logger.warning("Prerequisites check failed (but continuing anyway for baseline)")

    logger.info("=== GenAI Client Initialization ===")
    logger.info("GenAI client initialized (no instrumentation)")

    try:
        # Step: Clinical note summarization
        logger.info("=== Clinical Note Summarization ===")

        notes = MOCK_ENCOUNTERS[:3]

        cost_threshold = 0.05
        total_cost = 0.0

        for idx, note_text in enumerate(notes):
            logger.info(f"Processing Note #{idx + 1} (Preview: {note_text[:40]}...)")
            result = summarize_clinical_note(note_text)
            total_cost += result["cost_usd"]

            # Check cost threshold
            cost_per_1k = (result["cost_usd"] / result["total_tokens"]) * 1000
            if cost_per_1k > cost_threshold:
                logger.warning(
                    f"Cost: ${result['cost_usd']:.6f} (${cost_per_1k:.4f}/1k tokens - over threshold)"
                )
            else:
                logger.info(f"Cost: ${result['cost_usd']:.6f} (${cost_per_1k:.4f}/1k tokens)")

            logger.info(
                f"Tokens: {result['prompt_tokens']} prompt + {result['completion_tokens']} completion = {result['total_tokens']} total"
            )

        logger.info(f"Total estimated cost: ${total_cost:.6f}")

        # Step: Custom GenAI metrics (simulated)
        logger.info("=== Custom GenAI Metrics ===")
        logger.info("Cache hits: 5 (cache_type=semantic)")
        logger.info("Rate limit remaining: 4500 (provider=openai)")
        logger.info("Summary quality: 4.2 (model=gpt-3.5-turbo)")

        # Step: LLM error tracking
        logger.info("=== LLM Error Tracking ===")
        try:
            raise Exception("OpenAI API rate limit exceeded (429)")
        except Exception as e:
            logger.error(
                "LLM completion error: model=gpt-3.5-turbo, prompt_tokens=0, "
                "completion_tokens=0, latency=0.5, status=error"
            )
            logger.error(
                f"Error tracked: {type(e).__name__} - {str(e)}",
                extra={"provider": "openai", "model": "gpt-3.5-turbo", "error_code": "429"},
            )

        # Step: Completion
        logger.info("=== Execution Complete ===")
        print("✓ Telemetry sent to collector\n")

        # Step 12: Verification
        logger.info("=== Verify in GCP ===")
        logger.info("Cloud Logging: https://console.cloud.google.com/logs/query")
        logger.info('  Filter: logName="projects/bhsf-ai-team-projects/logs/emms-model-telemetry"')
        logger.info("\nCloud Trace: https://console.cloud.google.com/traces/list")
        logger.info("\nMetrics: genai.requests_total, genai.tokens_total, genai.cost_usd")
        logger.info("  Filter by: model=gpt-3.5-turbo")

    except Exception as e:
        logger.error(f"Error: {e}")
        raise


if __name__ == "__main__":
    main()
