import json
from pathlib import Path


def read_file_content(file_path: Path) -> str:
    ext = file_path.suffix.lower()

    if ext == ".pdf":
        return _read_pdf(file_path)
    elif ext in [".xlsx", ".xls"]:
        return _read_excel(file_path)
    elif ext == ".csv":
        return _read_csv(file_path)
    elif ext == ".json":
        return _read_json(file_path)
    else:
        return _read_text(file_path)


def _read_pdf(file_path: Path) -> str:
    try:
        import fitz  # PyMuPDF
        doc = fitz.open(str(file_path))
        text = ""
        for page in doc:
            text += page.get_text()
        doc.close()
        return text.strip()
    except ImportError:
        return f"[PDF file: {file_path.name} — install PyMuPDF: pip install pymupdf]"
    except Exception as e:
        return f"[PDF read error: {str(e)}]"


def _read_excel(file_path: Path) -> str:
    try:
        import openpyxl
        wb = openpyxl.load_workbook(str(file_path), read_only=True, data_only=True)
        output = []
        for sheet_name in wb.sheetnames:
            ws = wb[sheet_name]
            output.append(f"Sheet: {sheet_name}")
            for row in ws.iter_rows(values_only=True):
                row_data = [str(cell) if cell is not None else "" for cell in row]
                if any(row_data):
                    output.append("\t".join(row_data))
        wb.close()
        return "\n".join(output)
    except ImportError:
        return f"[XLSX file: {file_path.name} — install openpyxl: pip install openpyxl]"
    except Exception as e:
        return f"[XLSX read error: {str(e)}]"


def _read_csv(file_path: Path) -> str:
    try:
        with open(file_path, "r", encoding="utf-8", errors="replace") as f:
            return f.read()
    except Exception as e:
        return f"[CSV read error: {str(e)}]"


def _read_json(file_path: Path) -> str:
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return json.dumps(data, indent=2)
    except Exception as e:
        return f"[JSON read error: {str(e)}]"


def _read_text(file_path: Path) -> str:
    try:
        with open(file_path, "r", encoding="utf-8", errors="replace") as f:
            return f.read()
    except Exception as e:
        return f"[File read error: {str(e)}]"