import re
from pathlib import Path
from datetime import datetime
from typing import List
from rich.console import Console

console = Console()

def backup_file(file_path: Path) -> Path:
    """
    Make a timestamped backup copy of file_path if it exists.

    Returns the Path to the backup or original file.
    """
    if not file_path.exists():
        return file_path
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_path = file_path.with_name(f"{file_path.stem}_backup_{timestamp}{file_path.suffix}")
    backup_path.write_bytes(file_path.read_bytes())
    return backup_path

def insert_model_import(lines: List[str], model_name: str, models_path: Path) -> List[str]:
    """
    Insert a model import statement in source lines if not already present.
    """
    import_line = f"from {models_path.stem} import {model_name}  # autogenerated by Articuno\n"
    if any(import_line.strip() == line.strip() for line in lines):
        return lines
    last_import_idx = 0
    for i, line in enumerate(lines):
        stripped = line.strip()
        if stripped.startswith("import ") or stripped.startswith("from "):
            last_import_idx = i + 1
    lines.insert(last_import_idx, import_line)
    return lines

def find_and_modify_decorator_line(
    lines: List[str], func_name: str, model_name: str
) -> List[str]:
    """
    Modify FastAPI HTTP method decorator to include response_model=model_name.
    Remove old @infer_response_model decorators.
    """
    http_decorators = ["get", "post", "put", "patch", "delete", "options", "head"]
    new_lines = lines.copy()
    func_line_idx = None
    for i, line in enumerate(new_lines):
        if line.lstrip().startswith(f"def {func_name}"):
            func_line_idx = i
            break
    if func_line_idx is None:
        return new_lines
    for i in range(func_line_idx - 1, -1, -1):
        stripped = new_lines[i].lstrip()
        if stripped.startswith("@infer_response_model"):
            new_lines[i] = ""
        elif any(stripped.startswith(f"@app.{method}(") for method in http_decorators):
            if "response_model=" not in new_lines[i]:
                new_lines[i] = re.sub(
                    r"\)$",
                    f", response_model={model_name})",
                    new_lines[i]
                )
            break
    return new_lines
