"""src.sanitizer.sanitize_code_output の単体テスト.

LLM 出力からマークダウンフェンス・自然言語の前置き/後置きを除去して
純粋なソースコードを取り出すロジックを検証する（変換結果ファイルの
品質に直結する純粋関数）。
"""
from __future__ import annotations

import pathlib
import sys

ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from src.sanitizer import sanitize_code_output


def test_empty_input_returns_empty():
    assert sanitize_code_output("") == ""
    assert sanitize_code_output("   \n  ") == ""


def test_plain_code_gets_single_trailing_newline():
    assert sanitize_code_output("print('hi')") == "print('hi')\n"


def test_strips_markdown_fence_with_language():
    text = "```python\nprint('hi')\n```"
    assert sanitize_code_output(text) == "print('hi')\n"


def test_strips_bare_fence():
    text = "```\nx = 1\n```"
    assert sanitize_code_output(text) == "x = 1\n"


def test_removes_english_preamble():
    text = "Here is the converted code:\nprint('hi')"
    assert sanitize_code_output(text) == "print('hi')\n"


def test_removes_japanese_preamble():
    text = "以下が変換結果です。\nprint('hi')"
    assert sanitize_code_output(text) == "print('hi')\n"


def test_removes_english_epilogue():
    text = "print('hi')\nKey changes: replaced foo with bar."
    assert sanitize_code_output(text) == "print('hi')\n"


def test_removes_japanese_epilogue():
    text = "print('hi')\n主な変更: foo を bar に置換しました。"
    assert sanitize_code_output(text) == "print('hi')\n"


def test_removes_horizontal_rule_epilogue():
    text = "print('hi')\n---\nfooter text"
    assert sanitize_code_output(text) == "print('hi')\n"


def test_preamble_and_fence_combined():
    text = "Here is the code:\n```js\nconsole.log(1);\n```"
    assert sanitize_code_output(text) == "console.log(1);\n"


def test_internal_blank_lines_preserved():
    text = "def a():\n    pass\n\n\ndef b():\n    pass"
    out = sanitize_code_output(text)
    assert "def a():" in out and "def b():" in out
    # 末尾は単一改行
    assert out.endswith("pass\n")


def test_trailing_whitespace_trimmed_per_line():
    text = "x = 1   \ny = 2\t\t"
    assert sanitize_code_output(text) == "x = 1\ny = 2\n"


def test_code_with_internal_hash_not_treated_as_preamble():
    # "Note:" 風でないコメントは残る
    text = "# normal comment\nprint('hi')"
    out = sanitize_code_output(text)
    assert "# normal comment" in out
