"""
Report generation utilities for leakage analysis.
Provides concise console summaries and detailed Markdown reports.
"""
from . import analyze_dataset
from .analysis import LeakageAnalysisResult

# Console Summary (Quick Overview)
def print_leakage_report(result: LeakageAnalysisResult) -> None:
    """
    Print a concise summary of leakage analysis to the console.

    Parameters
    ----------
    result : LeakageAnalysisResult
        Result object returned by analyze_dataset().

    Examples
    --------
    >>> result = analyze_dataset(
    ...     df,
    ...     split_mode="temporal",
    ...     time_column="date",
    ...     id_columns=["device_id"]
    ... )
    >>> print_leakage_report(result)
    """

    print("DATA LEAKAGE SUMMARY")

    print(f"Leakage Score (L̃): {result.leakage_score:.4f}")

    exact = result.exact_duplicate_summary
    near = result.near_duplicate_summary

    print("\nDuplicate Analysis:")
    print(f"  Exact duplicates: {exact.exact_duplicate_rows} "
          f"({exact.exact_duplicate_percentage:.2f}%)")
    print(f"  Near-duplicate pairs: {near.near_duplicate_pairs}")
    print(f"  Affected rows: {near.affected_rows} "
          f"({near.affected_percentage:.2f}%)")
    print(f"Total rows (original): {result.metadata['total_rows']:,}")
    if result.metadata.get('sampling_applied'):
        print(f"  Analyzed rows (sampled): {result.metadata['analyzed_rows']:,}")
        print(f"  Sampling applied: Yes")
    else:
        print(f"  Sampling applied: No")


    print("\nSplit Information:")
    for key, value in result.split_info.items():
        print(f"  {key}: {value}")

    if result.overlap_info is not None:
        print("\nIdentifier Overlap:")
        print(result.overlap_info.to_string(index=False))

# Detailed Markdown Report
def save_report_to_file(
    result: LeakageAnalysisResult,
    path: str,
) -> None:
    """
    Save a detailed Markdown leakage report including interpretation.

    Parameters
    ----------
    result : LeakageAnalysisResult
        Result object returned by analyze_dataset().
    path : str
        Output Markdown file path.

    Examples
    --------
    >>> result = analyze_dataset(
    ...     df,
    ...     split_mode="temporal",
    ...     time_column="date",
    ...     id_columns=["device_id"]
    ...  )
    >>> save_report_to_file(result, "leakage_report.md")
    """

    interpretation = _interpret_leakage(result.leakage_score)

    exact = result.exact_duplicate_summary
    near = result.near_duplicate_summary

    overlap_md = "```\n" + result.overlap_info.to_string(index=False) + "\n```"


    content = f"""
# Data Leakage Analysis Report

---

## 1. Leakage Score

**Normalized Leakage (L̃): {result.leakage_score:.4f}**

### Interpretation

{interpretation}

---

## 2. Metadata

"""

    for key, value in result.metadata.items():
        content += f"- **{key}**: {value}\n"

    content += f"""
    
---

## 3. Duplicate Analysis

### Exact Duplicates
- Total rows analyzed: {exact.n_rows}
- Exact duplicate rows: {exact.exact_duplicate_rows}
- Percentage: {exact.exact_duplicate_percentage:.2f}%

### Near Duplicates
- Near-duplicate pairs: {near.near_duplicate_pairs}
- Affected rows: {near.affected_rows}
- Percentage of dataset: {near.affected_percentage:.2f}%
- Similarity threshold: {near.similarity_threshold}

---

## 4. Split Information

"""

    for key, value in result.split_info.items():
        content += f"- **{key}**: {value}\n"

    content += f"""

---

## 5. Identifier Overlap

{overlap_md}

---

## 6. Recommendations

- Consider temporal or group-based splitting if leakage is moderate or high.
- Increase temporal gap to reduce time-based proximity effects.
- Remove near-duplicates if evaluation optimism is suspected.
- Verify identifier overlap to ensure realistic deployment scenarios.

"""

    with open(path, "w", encoding="utf-8") as f:
        f.write(content)

# Interpretation Logic (Paper-Aligned)
def _interpret_leakage(score: float) -> str:
    """
    Interpret leakage score according to ICPE paper intuition.
    """

    if score == 0:
        return (
            "No measurable leakage detected. "
            "Training and test sets appear cleanly separated."
        )

    elif score < 0.2:
        return (
            "Low leakage detected. Minor temporal proximity effects may exist, "
            "but evaluation is likely reliable."
        )

    elif score < 0.5:
        return (
            "Moderate leakage detected. The evaluation setup may introduce "
            "optimistic bias due to temporal or group overlap."
        )

    else:
        return (
            "High leakage detected. The dataset split likely introduces "
            "significant temporal or group leakage, potentially leading to "
            "strongly over-optimistic performance estimates."
        )
