"""
Petition Service — AI-assisted legal petition drafting using Gemini.
Generates structured Pakistani civil law petitions based on case context.
"""
from typing import Optional
from sqlalchemy.orm import Session

from ..models.models import Case
from ..models.fyp2_models import DraftedPetition
from ..services.ai_service import call_with_retry

PETITION_TYPES = [
    "Civil Suit",
    "Application for Injunction",
    "Declaratory Suit",
    "Suit for Specific Performance",
    "Eviction Petition",
    "Recovery Suit",
    "Family Court Petition",
    "Appeal Memorandum",
    "Writ Petition",
]


def draft_petition(
    db: Session,
    case_id: int,
    lawyer_id: int,
    petition_type: str,
    additional_instructions: str = "",
) -> Optional["DraftedPetition"]:
    """
    Use Gemini to draft a formatted legal petition for the given case.
    Saves the result as DraftedPetition and returns it.
    """
    case = db.query(Case).filter(Case.id == case_id).first()
    if not case:
        return None

    prompt = _build_petition_prompt(case, petition_type, additional_instructions)

    try:
        petition_text = call_with_retry(
            prompt,
            {"temperature": 0.3, "max_output_tokens": 2048},
        )
    except Exception as e:
        print(f"[Petition] AI drafting failed: {e}")
        petition_text = _get_petition_template(case, petition_type)

    # Determine next version number for this case
    existing_count = db.query(DraftedPetition).filter(
        DraftedPetition.case_id == case_id,
        DraftedPetition.petition_type == petition_type,
    ).count()
    version = existing_count + 1

    petition = DraftedPetition(
        case_id=case_id,
        lawyer_id=lawyer_id,
        petition_type=petition_type,
        content=petition_text,
        version=version,
    )
    db.add(petition)
    db.commit()
    db.refresh(petition)
    return petition


def _build_petition_prompt(case: "Case", petition_type: str, extra: str) -> str:
    """Build the Gemini prompt for petition drafting."""
    case_ref = getattr(case, "case_reference_no", f"Case #{case.id}")
    opposing = getattr(case, "opposing_party", "Respondent")
    district = getattr(case, "district", "Lahore")
    relief = getattr(case, "relief_sought", "as prayed")

    extra_block = f"\nAdditional lawyer instructions: {extra}" if extra else ""

    return f"""You are a senior Pakistani civil law advocate. Draft a formal {petition_type} for the following case.

CASE REFERENCE: {case_ref}
CASE CATEGORY: {case.category or 'Civil Matter'}
DISTRICT / JURISDICTION: {district}
OPPOSING PARTY: {opposing}
RELIEF SOUGHT: {relief}
CASE DESCRIPTION: {case.description[:800]}
AI CASE SUMMARY: {case.summary or 'See description above'}{extra_block}

Write a professionally formatted Pakistani legal petition with these exact sections:
1. IN THE COURT OF CIVIL JUDGE / [relevant court], [DISTRICT]
2. TITLE (Petitioner vs Respondent)
3. BRIEF FACTS
4. CAUSE OF ACTION
5. LEGAL GROUNDS (cite relevant Pakistani laws and sections)
6. PRAYER / RELIEF SOUGHT
7. VERIFICATION CLAUSE

Use formal legal language. Reference applicable Pakistani laws (Transfer of Property Act, CPC, Specific Relief Act, Muslim Family Laws Ordinance, etc.) where relevant.
Do NOT include placeholder brackets — write realistic content based on the case description.
"""


def _get_petition_template(case: "Case", petition_type: str) -> str:
    """Fallback template when AI is unavailable."""
    case_ref = getattr(case, "case_reference_no", f"Case #{case.id}")
    district = getattr(case, "district", "[District]")
    opposing = getattr(case, "opposing_party", "Respondent")
    return f"""IN THE COURT OF CIVIL JUDGE, {district.upper()}

{petition_type.upper()}

Case Reference: {case_ref}
Category: {case.category}

BETWEEN:
[CLIENT NAME]                    ... PETITIONER

AND:
{opposing}                       ... RESPONDENT

BRIEF FACTS:
{case.description[:400]}

CAUSE OF ACTION:
The cause of action arose when the Respondent [describe the breach or act].

LEGAL GROUNDS:
The Petitioner relies upon the provisions of [relevant Act] and the established principles of Pakistani civil law.

PRAYER:
It is therefore most respectfully prayed that this Honourable Court may be pleased to:
1. {getattr(case, 'relief_sought', 'Grant the relief as prayed')}
2. Award costs of this petition to the Petitioner.
3. Grant any other relief deemed appropriate in the circumstances.

VERIFICATION:
I, [Client Name], the Petitioner above-named, do hereby solemnly affirm that the contents of this petition are true and correct to the best of my knowledge and belief.

Date: _______________                    Advocate for the Petitioner
Place: {district}
"""


def get_petition_versions(db: Session, case_id: int) -> list:
    """Return all drafted petitions for a case, newest first."""
    return (
        db.query(DraftedPetition)
        .filter(DraftedPetition.case_id == case_id)
        .order_by(DraftedPetition.created_at.desc())
        .all()
    )
