"""
NOMAZRA Extra Views — Smart Legal Intake Form + Offline Content.
These are the two remaining missing feature endpoints.
"""
import logging
import os
import json

from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.utils import timezone

logger = logging.getLogger(__name__)


# ──────────────────── SMART LEGAL INTAKE FORM ────────────────────

LEGAL_AREAS = [
    'civil', 'criminal', 'family', 'labor', 'property',
    'business', 'immigration', 'tax', 'constitutional',
    'traffic', 'consumer', 'other',
]

URGENCY_LEVELS = ['emergency', 'urgent', 'normal', 'informational']

INTAKE_QUESTIONS = {
    'general': [
        {'id': 'legal_area', 'question': 'What area of law does your issue relate to?', 'type': 'select', 'options': LEGAL_AREAS, 'required': True},
        {'id': 'country', 'question': 'Which country/jurisdiction is this about?', 'type': 'text', 'required': True},
        {'id': 'urgency', 'question': 'How urgent is this matter?', 'type': 'select', 'options': URGENCY_LEVELS, 'required': True},
        {'id': 'description', 'question': 'Describe your legal situation in detail.', 'type': 'textarea', 'required': True},
        {'id': 'parties', 'question': 'Who are the parties involved? (e.g., employer, landlord, spouse)', 'type': 'text', 'required': False},
        {'id': 'incident_date', 'question': 'When did this issue begin or occur?', 'type': 'date', 'required': False},
        {'id': 'amount', 'question': 'Is there a monetary amount involved? If so, how much?', 'type': 'text', 'required': False},
        {'id': 'prior_action', 'question': 'Have you taken any legal action so far?', 'type': 'textarea', 'required': False},
        {'id': 'documents', 'question': 'Do you have any relevant documents (contracts, notices, court papers)?', 'type': 'select', 'options': ['yes', 'no'], 'required': False},
        {'id': 'desired_outcome', 'question': 'What outcome are you hoping for?', 'type': 'textarea', 'required': False},
    ],
    'criminal': [
        {'id': 'charge_type', 'question': 'What are the charges or allegations?', 'type': 'text', 'required': True},
        {'id': 'arrest_date', 'question': 'Date of arrest or citation?', 'type': 'date', 'required': False},
        {'id': 'court_date', 'question': 'Is there a scheduled court date?', 'type': 'date', 'required': False},
        {'id': 'bail_status', 'question': 'Current bail/bond status?', 'type': 'select', 'options': ['not_arrested', 'released_on_bail', 'in_custody', 'released_own_recognizance'], 'required': False},
    ],
    'family': [
        {'id': 'matter_type', 'question': 'What type of family matter?', 'type': 'select', 'options': ['divorce', 'child_custody', 'child_support', 'adoption', 'domestic_violence', 'other'], 'required': True},
        {'id': 'children', 'question': 'Are minor children involved?', 'type': 'select', 'options': ['yes', 'no'], 'required': True},
        {'id': 'marriage_duration', 'question': 'Duration of marriage (if applicable)?', 'type': 'text', 'required': False},
    ],
    'labor': [
        {'id': 'employment_status', 'question': 'Current employment status?', 'type': 'select', 'options': ['employed', 'fired', 'resigned', 'laid_off', 'on_leave', 'contractor'], 'required': True},
        {'id': 'employer_size', 'question': 'Approximate size of employer?', 'type': 'select', 'options': ['1-10', '11-50', '51-250', '250+', 'government'], 'required': False},
        {'id': 'issue_type', 'question': 'What is the employment issue?', 'type': 'select', 'options': ['wrongful_termination', 'discrimination', 'harassment', 'wage_theft', 'benefits', 'safety', 'contract_dispute', 'other'], 'required': True},
    ],
    'property': [
        {'id': 'property_type', 'question': 'Type of property?', 'type': 'select', 'options': ['residential_rental', 'commercial_rental', 'home_purchase', 'land', 'commercial_property'], 'required': True},
        {'id': 'role', 'question': 'Your role?', 'type': 'select', 'options': ['tenant', 'landlord', 'buyer', 'seller', 'owner'], 'required': True},
        {'id': 'issue_type', 'question': 'What is the issue?', 'type': 'select', 'options': ['eviction', 'repairs', 'deposit', 'lease_dispute', 'purchase_dispute', 'boundary', 'other'], 'required': True},
    ],
    'immigration': [
        {'id': 'visa_type', 'question': 'Current visa/immigration status?', 'type': 'text', 'required': True},
        {'id': 'goal', 'question': 'Immigration goal?', 'type': 'select', 'options': ['work_visa', 'residency', 'citizenship', 'asylum', 'family_reunion', 'deportation_defense', 'other'], 'required': True},
        {'id': 'deadline', 'question': 'Any upcoming deadlines?', 'type': 'date', 'required': False},
    ],
    'business': [
        {'id': 'business_type', 'question': 'Type of business?', 'type': 'select', 'options': ['sole_proprietorship', 'partnership', 'llc', 'corporation', 'nonprofit', 'not_yet_formed'], 'required': True},
        {'id': 'issue_type', 'question': 'Business legal issue?', 'type': 'select', 'options': ['formation', 'contracts', 'disputes', 'ip', 'compliance', 'employment', 'tax', 'other'], 'required': True},
    ],
}


@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def legal_intake(request):
    """
    GET: Returns the intake questionnaire (general + area-specific questions).
    POST: Processes intake answers and generates a structured legal brief for AI.
    """
    if request.method == 'GET':
        # Return questionnaire
        legal_area = request.query_params.get('area', '')
        questions = list(INTAKE_QUESTIONS['general'])

        if legal_area in INTAKE_QUESTIONS:
            questions.extend(INTAKE_QUESTIONS[legal_area])

        return Response({
            'questions': questions,
            'available_areas': LEGAL_AREAS,
            'urgency_levels': URGENCY_LEVELS,
        })

    # POST — process intake answers and generate structured brief
    answers = request.data.get('answers', {})
    if not answers:
        return Response({'error': 'answers required'}, status=status.HTTP_400_BAD_REQUEST)

    legal_area = answers.get('legal_area', 'general')
    country = answers.get('country', 'US')
    urgency = answers.get('urgency', 'normal')
    description = answers.get('description', '')

    if not description:
        return Response({'error': 'description is required'}, status=status.HTTP_400_BAD_REQUEST)

    # Build structured brief for AI
    brief_parts = [
        f"LEGAL AREA: {legal_area}",
        f"JURISDICTION: {country}",
        f"URGENCY: {urgency}",
        f"DESCRIPTION: {description}",
    ]

    # Add all non-empty optional fields
    for key, value in answers.items():
        if key not in ('legal_area', 'country', 'urgency', 'description') and value:
            label = key.replace('_', ' ').title()
            brief_parts.append(f"{label}: {value}")

    structured_brief = "\n".join(brief_parts)

    # Generate AI analysis of the intake
    try:
        import openai
        client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

        response = client.chat.completions.create(
            model='gpt-4o-mini',
            messages=[
                {
                    'role': 'system',
                    'content': (
                        'You are NOMAZRA, an AI legal assistant. Analyze this legal intake form and provide: '
                        '1) Identified legal issues, 2) Relevant legal areas, 3) Key questions to investigate, '
                        '4) Recommended next steps, 5) Urgency assessment. '
                        'Be thorough but concise. Never mention GPT, OpenAI, or ChatGPT. '
                        'Return JSON with keys: issues, legal_areas, key_questions, next_steps, urgency_assessment, '
                        'recommended_features (list of NOMAZRA features to use like "statute_checker", "cost_estimator", '
                        '"rights_cards", "document_analysis", "voice_consultation").'
                    ),
                },
                {
                    'role': 'user',
                    'content': f'Analyze this legal intake:\n\n{structured_brief}',
                },
            ],
            temperature=0.3,
            max_tokens=800,
            response_format={"type": "json_object"},
        )

        analysis = json.loads(response.choices[0].message.content)
    except Exception as e:
        logger.error("Intake AI analysis failed: %s", e)
        analysis = {
            'issues': ['Analysis pending — please consult with NOMAZRA chat for detailed advice.'],
            'legal_areas': [legal_area],
            'key_questions': [],
            'next_steps': ['Start a conversation with NOMAZRA AI for personalized legal guidance.'],
            'urgency_assessment': urgency,
            'recommended_features': ['chat'],
        }

    # Create a conversation with the structured brief as first message
    from .models import Conversation, Message

    conv = Conversation.objects.create(
        user=request.user,
        title=f"Legal Intake: {legal_area.title()} ({country})",
        country=country,
        legal_area=legal_area,
    )

    # Save intake as a system message
    Message.objects.create(
        conversation=conv,
        role='system',
        content=f"Legal Intake Form:\n{structured_brief}",
        input_type='text',
    )

    return Response({
        'conversation_id': str(conv.id),
        'structured_brief': structured_brief,
        'analysis': analysis,
        'message': 'Intake processed. Use the conversation to continue with AI legal advice.',
    }, status=status.HTTP_201_CREATED)


# ──────────────────── OFFLINE CONTENT ────────────────────

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def offline_content(request):
    """
    Returns pre-packaged offline content for the user's selected countries.
    Includes: emergency info, key rights summaries, common legal terms,
    and cached law snippets. Designed to be downloaded and cached by the app.
    """
    from .country_data import COUNTRIES
    from .glossary_data import GLOSSARY_TERMS
    from .models import RightsCard, GlossaryTerm

    country_code = request.query_params.get('country', 'US').upper()

    # 1. Emergency info for this country (COUNTRIES is a list of dicts)
    country_info = next((c for c in COUNTRIES if c.get('code') == country_code), {})
    emergency = country_info.get('emergency', '')

    # 2. Rights cards for this country
    rights_cards = list(
        RightsCard.objects.filter(
            country=country_code, is_active=True
        ).values('id', 'category', 'title', 'content', 'citations', 'tags')
    )

    # 3. Key glossary terms (top 100 most common)
    # First from DB
    db_terms = list(
        GlossaryTerm.objects.filter(
            country__in=['', country_code]
        ).values('term', 'definition', 'plain_language', 'area')[:100]
    )

    # Supplement with hardcoded terms if DB is sparse
    if len(db_terms) < 50:
        hardcoded = [
            {'term': t['term'], 'definition': t['definition'],
             'plain_language': t['plain_language'], 'area': t.get('area', '')}
            for t in GLOSSARY_TERMS[:100]
        ]
        # Merge without duplicates
        existing_terms = {t['term'].lower() for t in db_terms}
        for t in hardcoded:
            if t['term'].lower() not in existing_terms:
                db_terms.append(t)
                existing_terms.add(t['term'].lower())

    # 4. Quick legal guides per area
    legal_guides = _get_offline_guides(country_code)

    # 5. Country legal system overview
    legal_system = country_info.get('legal_system', 'Common Law')
    topics = country_info.get('topics', [])

    return Response({
        'country': country_code,
        'country_name': country_info.get('name', country_code),
        'legal_system': legal_system,
        'topics': topics,
        'emergency_info': emergency,
        'rights_cards': rights_cards,
        'glossary_terms': db_terms[:100],
        'legal_guides': legal_guides,
        'last_updated': timezone.now().isoformat(),
        'cache_duration_hours': 168,  # 7 days
    })


def _get_offline_guides(country_code):
    """
    Pre-built quick legal guides for offline access.
    These are short, factual summaries designed for offline reading.
    """
    # Universal guides (applicable everywhere with country variations)
    guides = [
        {
            'id': 'traffic_stop',
            'title': 'What to Do at a Traffic Stop',
            'category': 'traffic',
            'content': [
                'Pull over safely to the right side of the road.',
                'Turn off your engine and turn on interior lights if dark.',
                'Keep your hands visible on the steering wheel.',
                'You have the right to remain silent beyond providing identification.',
                'You can refuse a vehicle search in most jurisdictions.',
                'Ask if you are free to go — you are being detained only if told so.',
                'Record badge number and patrol car number.',
                'Do not argue with the officer — contest the ticket in court.',
            ],
        },
        {
            'id': 'arrested',
            'title': 'Your Rights If Arrested',
            'category': 'criminal',
            'content': [
                'You have the right to remain silent — use it.',
                'Ask for a lawyer immediately.',
                'Do not resist arrest, even if you believe it is unlawful.',
                'You do not have to consent to a search.',
                'You have the right to know the charges against you.',
                'You have the right to make a phone call.',
                'Do not sign anything without a lawyer present.',
                'Everything you say can and will be used against you.',
            ],
        },
        {
            'id': 'eviction_notice',
            'title': 'What to Do When Facing Eviction',
            'category': 'property',
            'content': [
                'Read the eviction notice carefully — note dates and reasons.',
                'Do NOT move out immediately unless ordered by a court.',
                'You have the right to contest an eviction in court.',
                'Check if the notice period is correct for your jurisdiction.',
                'Document the condition of the property with photos.',
                'Keep records of all rent payments.',
                'Seek free legal aid if you cannot afford a lawyer.',
                'Retaliation evictions (for complaints) are illegal in many places.',
            ],
        },
        {
            'id': 'fired_from_job',
            'title': 'What to Do If Fired',
            'category': 'labor',
            'content': [
                'Ask for the reason in writing.',
                'Request your final paycheck and any owed benefits.',
                'Do not sign a severance agreement without reviewing it.',
                'Check if the termination violates any anti-discrimination laws.',
                'File for unemployment benefits immediately.',
                'Save copies of your employment records, emails, and evaluations.',
                'Note any witnesses to the termination.',
                'Consult a labor attorney if you suspect wrongful termination.',
            ],
        },
        {
            'id': 'divorce_basics',
            'title': 'Divorce: Know Your Rights',
            'category': 'family',
            'content': [
                'Document all shared assets, debts, and property.',
                'Open a personal bank account if you do not have one.',
                'Gather copies of financial documents (taxes, bank statements, deeds).',
                'Do not move out of the marital home without legal advice.',
                'Child custody is decided based on the child\'s best interest.',
                'You may be entitled to spousal support/alimony.',
                'Mediation is often faster and cheaper than litigation.',
                'Keep communications with your spouse civil and documented.',
            ],
        },
        {
            'id': 'workplace_harassment',
            'title': 'Handling Workplace Harassment',
            'category': 'labor',
            'content': [
                'Document every incident: date, time, location, witnesses.',
                'Save all evidence (emails, messages, photos).',
                'Report to HR or your supervisor in writing.',
                'If HR does not act, file a complaint with the labor board.',
                'Retaliation for reporting harassment is illegal.',
                'You can file a formal legal complaint independently.',
                'Consult a labor attorney about your rights.',
                'Keep a personal log separate from work systems.',
            ],
        },
        {
            'id': 'consumer_rights',
            'title': 'Consumer Rights Basics',
            'category': 'consumer',
            'content': [
                'You have the right to a refund for defective products.',
                'False advertising is illegal — you can file a complaint.',
                'Read terms and conditions before signing up for services.',
                'You can dispute unauthorized charges with your bank.',
                'Cooling-off periods exist for door-to-door sales in many countries.',
                'Keep receipts and warranty documents.',
                'File complaints with your country\'s consumer protection agency.',
                'Small claims court is designed for consumer disputes.',
            ],
        },
        {
            'id': 'immigration_basics',
            'title': 'Immigration Rights',
            'category': 'immigration',
            'content': [
                'Always carry your immigration documents.',
                'You have the right to an interpreter in legal proceedings.',
                'Do not sign documents you do not understand.',
                'You can refuse to answer questions about your status to non-officials.',
                'You have the right to legal representation in immigration court.',
                'Know the number for your country\'s immigration legal aid.',
                'Keep copies of all immigration applications and correspondence.',
                'Deportation orders can be appealed — seek legal help immediately.',
            ],
        },
    ]

    return guides


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def offline_bundle(request):
    """
    Returns a complete offline data bundle with all rights cards
    and glossary terms for download. Compressed data for caching.
    """
    from .models import RightsCard, GlossaryTerm
    from .glossary_data import GLOSSARY_TERMS

    # All active rights cards
    cards = list(
        RightsCard.objects.filter(is_active=True).values(
            'id', 'country', 'category', 'title', 'content', 'citations', 'tags'
        )
    )

    # All glossary terms
    db_terms = list(
        GlossaryTerm.objects.all().values(
            'term', 'definition', 'plain_language', 'area'
        )
    )

    # Add hardcoded terms not in DB
    existing = {t['term'].lower() for t in db_terms}
    for t in GLOSSARY_TERMS:
        if t['term'].lower() not in existing:
            db_terms.append({
                'term': t['term'],
                'definition': t['definition'],
                'plain_language': t['plain_language'],
                'area': t.get('area', ''),
            })

    return Response({
        'rights_cards': cards,
        'glossary_terms': db_terms,
        'total_rights_cards': len(cards),
        'total_glossary_terms': len(db_terms),
        'last_updated': timezone.now().isoformat(),
        'version': '1.0.0',
    })
