"""
Baymax Workflow Orchestration
=============================
High-level workflows that chain multiple tools into single-call pipelines.
Each workflow maps to a discrete task in brief-writing.

Design principles:
- Fail gracefully: return partial results + error messages rather than nothing
- Each workflow = one task you'd do manually with 3-4 tool calls
- Output is ready-to-paste, not raw data
"""

import os
import re
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, field

# Import core extraction functions
from brief_synthesis import (
    read_case_file,
    synthesize_rules_across_cases,
    generate_parentheticals_for_cases,
    format_rule_hierarchy,
    format_parentheticals,
    _extract_citation_from_text,
    extract_structured_case_facts,
    generate_parenthetical,
    StructuredCaseFacts
)
from enhanced_rules import extract_enhanced_rules, EnhancedRule


@dataclass
class WorkflowResult:
    """Result container with partial results and error tracking."""
    success: bool
    output: str  # Formatted, ready-to-paste output
    errors: List[str] = field(default_factory=list)
    warnings: List[str] = field(default_factory=list)
    partial_results: Dict[str, Any] = field(default_factory=dict)


# ============================================================================
# WORKFLOW: SYNTHESIZE RULES
# ============================================================================

def workflow_synthesize_rules(
    file_paths: Optional[List[str]] = None,
    case_texts: Optional[Dict[str, Tuple[str, str]]] = None,
    issue: Optional[str] = None,
    jurisdiction: Optional[str] = None
) -> WorkflowResult:
    """
    Complete rule synthesis workflow in one call.

    Pipeline:
    1. Read all case files (if file_paths provided)
    2. Extract citation from each case text
    3. Extract rules from each case
    4. Synthesize rules across cases into hierarchy
    5. Generate parentheticals for each case
    6. Format everything into paste-ready RULE section

    Args:
        file_paths: List of paths to case files (PDF, DOCX, TXT)
        case_texts: Alternative to files - Dict of case_name -> (text, citation)
                   If citation is empty, will attempt to extract from text
        issue: Legal issue being briefed (helps focus extraction)
        jurisdiction: Your circuit (e.g., "5th Circuit") for binding/persuasive tagging

    Returns:
        WorkflowResult with formatted RULE section and parentheticals
    """
    result = WorkflowResult(success=False, output="")
    cases: Dict[str, Tuple[str, str]] = {}

    # =========================================================================
    # STEP 1: Load cases (from files or provided texts)
    # =========================================================================

    if file_paths:
        for file_path in file_paths:
            try:
                text, file_type = read_case_file(file_path)

                if not text or text.startswith("Error"):
                    result.warnings.append(f"Could not read: {file_path}")
                    continue

                # Extract case name from filename
                basename = os.path.basename(file_path)
                name_without_ext = os.path.splitext(basename)[0]
                case_name = re.sub(r'\s+v\s+', ' v. ', name_without_ext)
                case_name = re.sub(r'[_-]', ' ', case_name)

                # Try to extract citation from text
                citation = _extract_citation_from_text(text, case_name)
                if not citation:
                    result.warnings.append(
                        f"Could not extract citation for '{case_name}' - "
                        "consider providing citation in filename or text"
                    )
                    citation = ""

                cases[case_name] = (text, citation)

            except Exception as e:
                result.errors.append(f"Error reading {file_path}: {str(e)}")

    elif case_texts:
        for case_name, (text, citation) in case_texts.items():
            # If citation not provided, try to extract it
            if not citation:
                citation = _extract_citation_from_text(text, case_name) or ""
                if not citation:
                    result.warnings.append(
                        f"No citation for '{case_name}' - rules will lack proper citation"
                    )
            cases[case_name] = (text, citation)

    else:
        result.errors.append("Must provide either file_paths or case_texts")
        return result

    if not cases:
        result.errors.append("No valid cases could be loaded")
        return result

    result.partial_results["cases_loaded"] = list(cases.keys())

    # =========================================================================
    # STEP 2: Extract rules from each case
    # =========================================================================

    all_rules: Dict[str, List] = {}
    for case_name, (text, citation) in cases.items():
        try:
            rules = extract_enhanced_rules(text, case_name, citation)
            if rules:
                all_rules[case_name] = rules
            else:
                result.warnings.append(f"No rules extracted from '{case_name}'")
        except Exception as e:
            result.errors.append(f"Rule extraction failed for '{case_name}': {str(e)}")

    if not all_rules:
        result.errors.append("No rules could be extracted from any case")
        # Still try to continue with partial output

    result.partial_results["rules_extracted"] = {
        name: len(rules) for name, rules in all_rules.items()
    }

    # =========================================================================
    # STEP 3: Synthesize rules across cases
    # =========================================================================

    synthesis_output = ""
    try:
        hierarchy = synthesize_rules_across_cases(cases, issue, jurisdiction)
        if hierarchy:
            synthesis_output = format_rule_hierarchy(hierarchy, jurisdiction)
            result.partial_results["synthesis_rules"] = len(hierarchy)
        else:
            result.warnings.append(
                "Cross-case synthesis produced no results - "
                "cases may have too few overlapping rules"
            )
    except Exception as e:
        result.errors.append(f"Rule synthesis failed: {str(e)}")

    # =========================================================================
    # STEP 4: Generate parentheticals
    # =========================================================================

    parentheticals_output = ""
    try:
        parentheticals = generate_parentheticals_for_cases(cases)
        if parentheticals:
            parentheticals_output = format_parentheticals(parentheticals)
            result.partial_results["parentheticals_generated"] = len(parentheticals)
        else:
            result.warnings.append("Could not generate parentheticals")
    except Exception as e:
        result.errors.append(f"Parenthetical generation failed: {str(e)}")

    # =========================================================================
    # STEP 5: Format final output
    # =========================================================================

    output_sections = []

    # Header
    output_sections.append("=" * 70)
    output_sections.append("BAYMAX RULE SYNTHESIS WORKFLOW")
    output_sections.append("=" * 70)
    output_sections.append(f"Cases analyzed: {len(cases)}")
    if issue:
        output_sections.append(f"Issue: {issue}")
    if jurisdiction:
        output_sections.append(f"Jurisdiction: {jurisdiction}")
    output_sections.append("")

    # Synthesis results
    if synthesis_output:
        output_sections.append(synthesis_output)
    else:
        # Fallback: show individual rules if synthesis failed
        output_sections.append("\n[Synthesis failed - showing individual rules]\n")
        for case_name, rules in all_rules.items():
            case_cite = cases.get(case_name, ("", ""))[1]
            output_sections.append(f"\n=== {case_name} ===")
            if case_cite:
                output_sections.append(f"Citation: {case_cite}")
            for rule in rules[:5]:  # Top 5 rules per case
                output_sections.append(f"\n• {rule.text[:300]}...")
                if rule.elements:
                    output_sections.append(f"  Elements: {rule.elements[:3]}")

    # Parentheticals
    if parentheticals_output:
        output_sections.append("\n" + "=" * 70)
        output_sections.append(parentheticals_output)

    # Warnings and errors
    if result.warnings:
        output_sections.append("\n" + "-" * 70)
        output_sections.append("WARNINGS:")
        for w in result.warnings:
            output_sections.append(f"  ! {w}")

    if result.errors:
        output_sections.append("\n" + "-" * 70)
        output_sections.append("ERRORS (partial results returned):")
        for e in result.errors:
            output_sections.append(f"  X {e}")

    result.output = "\n".join(output_sections)
    result.success = bool(synthesis_output or all_rules)

    return result


# ============================================================================
# WORKFLOW: VALIDATE BRIEF
# ============================================================================

def workflow_validate_brief(
    brief_text: str,
    case_texts: Optional[Dict[str, str]] = None,
    check_citations: bool = True,
    check_parentheticals: bool = True,
    check_record_cites: bool = True,
    find_adverse: bool = True
) -> WorkflowResult:
    """
    Complete brief validation workflow - run all QC checks in one call.

    Pipeline:
    1. verify_citations - Check quoted language matches sources
    2. check_parenthetical_accuracy - Verify parentheticals match holdings
    3. validate_record_cites - Find factual claims without record support
    4. find_adverse_authority - Identify holdings that hurt your argument

    Args:
        brief_text: Your draft brief text
        case_texts: Dict of case_name -> case_text (needed for citation/parenthetical checks)
        check_citations: Run citation verification
        check_parentheticals: Run parenthetical accuracy check
        check_record_cites: Run record citation validation
        find_adverse: Run adverse authority detection

    Returns:
        WorkflowResult with comprehensive QC report
    """
    # Import validation functions
    try:
        from extraction_validation import (
            verify_citations_mcp,
            check_parenthetical_accuracy_mcp,
            find_adverse_authority_mcp
        )
        from brief_quality import validate_record_cites_mcp
        validation_available = True
    except ImportError:
        validation_available = False

    result = WorkflowResult(success=False, output="")

    if not validation_available:
        result.errors.append("Validation modules not available")
        return result

    output_sections = []
    output_sections.append("=" * 70)
    output_sections.append("BAYMAX BRIEF VALIDATION REPORT")
    output_sections.append("=" * 70)
    output_sections.append("")

    issues_found = 0
    checks_passed = 0
    total_checks = 0

    # =========================================================================
    # CHECK 1: Citation Verification
    # =========================================================================

    if check_citations and case_texts:
        total_checks += 1
        output_sections.append("\n## CITATION VERIFICATION")
        output_sections.append("-" * 40)

        try:
            citation_result = verify_citations_mcp(brief_text, case_texts)
            output_sections.append(citation_result)

            # Count issues (look for NOT_FOUND or CLOSE_MATCH)
            if "NOT_FOUND" in citation_result or "CLOSE_MATCH" in citation_result:
                issues_found += 1
                result.warnings.append("Some citations may not match source text")
            else:
                checks_passed += 1

            result.partial_results["citation_check"] = "complete"

        except Exception as e:
            result.errors.append(f"Citation verification failed: {str(e)}")
            output_sections.append(f"[Error: {str(e)}]")

    elif check_citations and not case_texts:
        output_sections.append("\n## CITATION VERIFICATION")
        output_sections.append("[Skipped - no case texts provided]")

    # =========================================================================
    # CHECK 2: Parenthetical Accuracy
    # =========================================================================

    if check_parentheticals and case_texts:
        total_checks += 1
        output_sections.append("\n## PARENTHETICAL ACCURACY")
        output_sections.append("-" * 40)

        try:
            # Extract parentheticals from brief
            paren_pattern = r'([A-Z][a-zA-Z\s]+(?:v\.?\s+[A-Z][a-zA-Z\s]+)?)[^(]*\(([^)]+(?:holding|finding|noting|explaining)[^)]*)\)'
            parentheticals = []
            for match in re.finditer(paren_pattern, brief_text):
                parentheticals.append({
                    "case_name": match.group(1).strip(),
                    "parenthetical_text": match.group(2).strip()
                })

            if parentheticals:
                paren_result = check_parenthetical_accuracy_mcp(parentheticals, case_texts)
                output_sections.append(paren_result)

                if "OVERSTATED" in paren_result or "UNSUPPORTED" in paren_result:
                    issues_found += 1
                    result.warnings.append("Some parentheticals may overstate or lack support")
                else:
                    checks_passed += 1
            else:
                output_sections.append("[No parentheticals found in brief]")
                checks_passed += 1

            result.partial_results["parenthetical_check"] = "complete"

        except Exception as e:
            result.errors.append(f"Parenthetical check failed: {str(e)}")
            output_sections.append(f"[Error: {str(e)}]")

    # =========================================================================
    # CHECK 3: Record Citations
    # =========================================================================

    if check_record_cites:
        total_checks += 1
        output_sections.append("\n## RECORD CITATION COVERAGE")
        output_sections.append("-" * 40)

        try:
            record_result = validate_record_cites_mcp(brief_text)
            output_sections.append(record_result)

            if "[NEED CITE" in record_result:
                issues_found += 1
                result.warnings.append("Some factual claims lack record support")
            else:
                checks_passed += 1

            result.partial_results["record_check"] = "complete"

        except Exception as e:
            result.errors.append(f"Record citation check failed: {str(e)}")
            output_sections.append(f"[Error: {str(e)}]")

    # =========================================================================
    # CHECK 4: Adverse Authority
    # =========================================================================

    if find_adverse and case_texts:
        total_checks += 1
        output_sections.append("\n## ADVERSE AUTHORITY SCAN")
        output_sections.append("-" * 40)

        try:
            # Extract argument sections from brief
            argument_text = brief_text  # Could be smarter about extracting just arguments

            adverse_result = find_adverse_authority_mcp(argument_text, case_texts)
            output_sections.append(adverse_result)

            if "FATAL" in adverse_result or "SERIOUS" in adverse_result:
                issues_found += 1
                result.warnings.append("Potentially adverse authority detected")
            else:
                checks_passed += 1

            result.partial_results["adverse_check"] = "complete"

        except Exception as e:
            result.errors.append(f"Adverse authority check failed: {str(e)}")
            output_sections.append(f"[Error: {str(e)}]")

    # =========================================================================
    # SUMMARY
    # =========================================================================

    output_sections.append("\n" + "=" * 70)
    output_sections.append("VALIDATION SUMMARY")
    output_sections.append("=" * 70)
    output_sections.append(f"Checks run: {total_checks}")
    output_sections.append(f"Checks passed: {checks_passed}")
    output_sections.append(f"Issues found: {issues_found}")

    if issues_found == 0 and total_checks > 0:
        output_sections.append("\n[OK] Brief passes all validation checks")
    elif issues_found > 0:
        output_sections.append(f"\n[!] {issues_found} issue(s) require attention before filing")

    if result.errors:
        output_sections.append("\nErrors during validation:")
        for e in result.errors:
            output_sections.append(f"  X {e}")

    result.output = "\n".join(output_sections)
    result.success = total_checks > 0 and len(result.errors) == 0

    return result


# ============================================================================
# WORKFLOW: BRIEF THIS CASE
# ============================================================================

def workflow_brief_this_case(
    file_path: Optional[str] = None,
    case_text: Optional[str] = None,
    case_name: Optional[str] = None,
    citation: Optional[str] = None
) -> WorkflowResult:
    """
    Comprehensive single-case briefing workflow - extract everything in one call.

    Pipeline:
    1. Read case file (if file_path provided)
    2. Extract/validate citation
    3. Extract structured facts (operative, determinative, disputed, etc.)
    4. Extract rules and holdings
    5. Generate parenthetical
    6. Format into complete case brief

    Args:
        file_path: Path to case file (PDF, DOCX, TXT)
        case_text: Alternative to file - raw case text
        case_name: Case name (extracted from filename if not provided)
        citation: Full citation (extracted from text if not provided)

    Returns:
        WorkflowResult with formatted case brief containing facts, rules, and parenthetical
    """
    result = WorkflowResult(success=False, output="")
    text = ""

    # =========================================================================
    # STEP 1: Load case text
    # =========================================================================

    if file_path:
        try:
            text, file_type = read_case_file(file_path)
            if not text or text.startswith("Error"):
                result.errors.append(f"Could not read file: {file_path}")
                return result

            # Extract case name from filename if not provided
            if not case_name:
                basename = os.path.basename(file_path)
                name_without_ext = os.path.splitext(basename)[0]
                case_name = re.sub(r'\s+v\s+', ' v. ', name_without_ext)
                case_name = re.sub(r'[_-]', ' ', case_name)

            result.partial_results["file_loaded"] = file_path
            result.partial_results["file_type"] = file_type

        except Exception as e:
            result.errors.append(f"Error reading file: {str(e)}")
            return result

    elif case_text:
        text = case_text
        if not case_name:
            case_name = "Unknown Case"
            result.warnings.append("No case name provided - using 'Unknown Case'")
    else:
        result.errors.append("Must provide either file_path or case_text")
        return result

    # =========================================================================
    # STEP 2: Extract/validate citation
    # =========================================================================

    if not citation:
        citation = _extract_citation_from_text(text, case_name) or ""
        if citation:
            result.partial_results["citation_extracted"] = True
        else:
            result.warnings.append(
                "Could not extract citation from text - "
                "provide citation parameter for proper formatting"
            )
            result.partial_results["citation_extracted"] = False

    # =========================================================================
    # STEP 3: Extract structured facts
    # =========================================================================

    facts_data = None
    try:
        facts_data = extract_structured_case_facts(text)
        if facts_data:
            result.partial_results["facts_extracted"] = True
            # Count what we got
            fact_counts = {}
            if facts_data.operative_facts:
                fact_counts["operative"] = len(facts_data.operative_facts)
            if facts_data.determinative_facts:
                fact_counts["determinative"] = len(facts_data.determinative_facts)
            if facts_data.disputed_facts:
                fact_counts["disputed"] = len(facts_data.disputed_facts)
            if facts_data.undisputed_facts:
                fact_counts["undisputed"] = len(facts_data.undisputed_facts)
            result.partial_results["fact_counts"] = fact_counts
        else:
            result.warnings.append("Could not extract structured facts")
            result.partial_results["facts_extracted"] = False
    except Exception as e:
        result.errors.append(f"Fact extraction failed: {str(e)}")

    # =========================================================================
    # STEP 4: Extract rules and holdings
    # =========================================================================

    rules = []
    try:
        rules = extract_enhanced_rules(text, case_name, citation)
        if rules:
            result.partial_results["rules_extracted"] = len(rules)
            # Categorize by type
            rule_types = {}
            for rule in rules:
                rtype = rule.rule_type.name if hasattr(rule.rule_type, 'name') else str(rule.rule_type)
                rule_types[rtype] = rule_types.get(rtype, 0) + 1
            result.partial_results["rule_types"] = rule_types
        else:
            result.warnings.append("No rules extracted from case")
            result.partial_results["rules_extracted"] = 0
    except Exception as e:
        result.errors.append(f"Rule extraction failed: {str(e)}")

    # =========================================================================
    # STEP 5: Generate parenthetical
    # =========================================================================

    parenthetical = ""
    try:
        # Note: signature is generate_parenthetical(case_name, case_text, citation)
        paren_obj = generate_parenthetical(case_name, text, citation)
        if paren_obj:
            # Parenthetical dataclass uses parenthetical_text, not text
            if hasattr(paren_obj, 'parenthetical_text'):
                parenthetical = paren_obj.parenthetical_text
            elif hasattr(paren_obj, 'text'):
                parenthetical = paren_obj.text
            else:
                parenthetical = str(paren_obj)
            result.partial_results["parenthetical_generated"] = True
        else:
            result.warnings.append("Could not generate parenthetical")
            result.partial_results["parenthetical_generated"] = False
    except Exception as e:
        result.errors.append(f"Parenthetical generation failed: {str(e)}")

    # =========================================================================
    # STEP 6: Format comprehensive output
    # =========================================================================

    output_sections = []

    # Header
    output_sections.append("=" * 70)
    output_sections.append("BAYMAX CASE BRIEF")
    output_sections.append("=" * 70)
    output_sections.append("")

    # Case identification
    output_sections.append(f"CASE: {case_name}")
    if citation:
        output_sections.append(f"CITATION: {citation}")
    output_sections.append("")

    # Procedural posture
    if facts_data and facts_data.procedural_posture:
        output_sections.append("-" * 70)
        output_sections.append("PROCEDURAL POSTURE")
        output_sections.append("-" * 70)
        output_sections.append(facts_data.procedural_posture)
        output_sections.append("")

    # Facts section
    output_sections.append("-" * 70)
    output_sections.append("FACTS")
    output_sections.append("-" * 70)

    if facts_data:
        if facts_data.operative_facts:
            output_sections.append("\n[OPERATIVE FACTS]")
            for i, fact in enumerate(facts_data.operative_facts, 1):
                output_sections.append(f"  {i}. {fact}")

        if facts_data.determinative_facts:
            output_sections.append("\n[DETERMINATIVE FACTS - Key to Outcome]")
            for i, fact in enumerate(facts_data.determinative_facts, 1):
                output_sections.append(f"  {i}. {fact}")

        if facts_data.disputed_facts:
            output_sections.append("\n[DISPUTED FACTS]")
            for i, fact in enumerate(facts_data.disputed_facts, 1):
                output_sections.append(f"  {i}. {fact}")

        if facts_data.undisputed_facts:
            output_sections.append("\n[UNDISPUTED FACTS]")
            for i, fact in enumerate(facts_data.undisputed_facts, 1):
                output_sections.append(f"  {i}. {fact}")

        if facts_data.insufficient_facts:
            output_sections.append("\n[INSUFFICIENT FACTS - Noted by Court]")
            for i, fact in enumerate(facts_data.insufficient_facts, 1):
                output_sections.append(f"  {i}. {fact}")
    else:
        output_sections.append("  [No structured facts extracted]")

    output_sections.append("")

    # Rules/Holdings section
    output_sections.append("-" * 70)
    output_sections.append("RULES & HOLDINGS")
    output_sections.append("-" * 70)

    if rules:
        # Group by type for cleaner output
        holdings = [r for r in rules if hasattr(r, 'rule_type') and
                   r.rule_type.name in ('HOLDING', 'NARROW_HOLDING')]
        standards = [r for r in rules if hasattr(r, 'rule_type') and
                    r.rule_type.name in ('STANDARD', 'TEST')]
        elements = [r for r in rules if hasattr(r, 'rule_type') and
                   r.rule_type.name == 'ELEMENT']
        other_rules = [r for r in rules if r not in holdings + standards + elements]

        if holdings:
            output_sections.append("\n[HOLDINGS]")
            for i, rule in enumerate(holdings, 1):
                cite_str = f" ({rule.pinpoint_page})" if rule.pinpoint_page else ""
                output_sections.append(f"  {i}. {rule.text}{cite_str}")

        if standards:
            output_sections.append("\n[STANDARDS/TESTS]")
            for i, rule in enumerate(standards, 1):
                output_sections.append(f"  {i}. {rule.text}")
                if rule.elements:
                    for j, elem in enumerate(rule.elements, 1):
                        output_sections.append(f"      ({j}) {elem}")

        if elements:
            output_sections.append("\n[ELEMENTS]")
            for i, rule in enumerate(elements, 1):
                output_sections.append(f"  {i}. {rule.text}")

        if other_rules:
            output_sections.append("\n[OTHER RULES]")
            for i, rule in enumerate(other_rules[:5], 1):  # Limit to 5
                output_sections.append(f"  {i}. {rule.text[:300]}...")
    else:
        output_sections.append("  [No rules extracted]")

    output_sections.append("")

    # Outcome
    if facts_data and facts_data.outcome:
        output_sections.append("-" * 70)
        output_sections.append("OUTCOME")
        output_sections.append("-" * 70)
        output_sections.append(facts_data.outcome)
        output_sections.append("")

    # Parenthetical
    output_sections.append("-" * 70)
    output_sections.append("PARENTHETICAL")
    output_sections.append("-" * 70)
    if parenthetical:
        if citation:
            output_sections.append(f"{case_name}, {citation} ({parenthetical})")
        else:
            output_sections.append(f"{case_name} ({parenthetical})")
    else:
        output_sections.append("[No parenthetical generated]")

    # Warnings and errors
    if result.warnings:
        output_sections.append("\n" + "-" * 70)
        output_sections.append("EXTRACTION NOTES:")
        for w in result.warnings:
            output_sections.append(f"  ! {w}")

    if result.errors:
        output_sections.append("\n" + "-" * 70)
        output_sections.append("ERRORS (partial results returned):")
        for e in result.errors:
            output_sections.append(f"  X {e}")

    result.output = "\n".join(output_sections)
    result.success = bool(rules or facts_data)

    return result


# ============================================================================
# MCP INTERFACE FUNCTIONS
# ============================================================================

def workflow_brief_this_case_mcp(
    file_path: Optional[str] = None,
    case_text: Optional[str] = None,
    case_name: Optional[str] = None,
    citation: Optional[str] = None
) -> str:
    """MCP-compatible wrapper that returns formatted string."""
    result = workflow_brief_this_case(
        file_path=file_path,
        case_text=case_text,
        case_name=case_name,
        citation=citation
    )
    return result.output


def workflow_synthesize_rules_mcp(
    file_paths: Optional[List[str]] = None,
    case_texts: Optional[Dict[str, List[str]]] = None,
    issue: Optional[str] = None,
    jurisdiction: Optional[str] = None
) -> str:
    """MCP-compatible wrapper that returns formatted string."""

    # Convert case_texts from MCP format [text, citation] to tuple
    converted_texts = None
    if case_texts:
        converted_texts = {}
        for name, data in case_texts.items():
            if isinstance(data, list) and len(data) >= 2:
                converted_texts[name] = (data[0], data[1])
            elif isinstance(data, list) and len(data) == 1:
                converted_texts[name] = (data[0], "")
            else:
                converted_texts[name] = (str(data), "")

    result = workflow_synthesize_rules(
        file_paths=file_paths,
        case_texts=converted_texts,
        issue=issue,
        jurisdiction=jurisdiction
    )

    return result.output


def workflow_validate_brief_mcp(
    brief_text: str,
    case_texts: Optional[Dict[str, str]] = None,
    check_citations: bool = True,
    check_parentheticals: bool = True,
    check_record_cites: bool = True,
    find_adverse: bool = True
) -> str:
    """MCP-compatible wrapper that returns formatted string."""

    result = workflow_validate_brief(
        brief_text=brief_text,
        case_texts=case_texts,
        check_citations=check_citations,
        check_parentheticals=check_parentheticals,
        check_record_cites=check_record_cites,
        find_adverse=find_adverse
    )

    return result.output
