"""Sidecar init — generate initial .claude/ files for bare projects."""
from ...models.sidecar import InitResult, LLMInitResponse
from ...sidecar.prompts import INIT_SYSTEM, INIT_USER


class InitMixin:
    """Project initialization — generate CLAUDE.md + rules from scan."""

    def init_project(self) -> InitResult:
        """Generate initial .claude/ files for a project that has none."""
        project_root = self._claude_dir.parent

        # Check both common locations
        for candidate in ("CLAUDE.md", ".claude/CLAUDE.md"):
            p = project_root / candidate
            if p.exists() and p.stat().st_size > 50:
                return InitResult(
                    files_created=[],
                    tokens_used=0,
                    model_used=f"skipped — {candidate} already exists",
                )

        scan_result = self.scan()
        deps_block = ", ".join(scan_result.dependencies) or "(none detected)"
        dirs_block = ", ".join(scan_result.top_dirs) or "(none)"
        commits_block = "\n".join(scan_result.recent_commits[:10]) or "(no git history)"

        entry_points = "unknown"
        try:
            from ...sidecar.exclusions import scan_project_dirs
            dirs = scan_project_dirs(project_root, max_depth=2, max_dirs=20)
            _ENTRY_NAMES = {"main.py", "app.py", "index.ts", "index.js", "server.py", "server.ts", "main.go", "main.rs"}
            entries = []
            for d in dirs:
                for f in d.file_names:
                    if f in _ENTRY_NAMES:
                        path = f"{d.path}/{f}" if d.path != "." else f
                        entries.append(path)
            entry_points = ", ".join(entries) if entries else "none detected"
        except Exception:
            pass

        user_msg = INIT_USER.format(
            deps_block=deps_block,
            dirs_block=dirs_block,
            commits_block=commits_block,
            entry_points=entry_points,
        )

        response = self._sdk.parse(
            model=self._model,
            messages=[
                {"role": "system", "content": INIT_SYSTEM},
                {"role": "user", "content": user_msg},
            ],
            response_format=LLMInitResponse,
            temperature=0.3,
        )

        tokens_used = response.usage.total_tokens if response.usage else 0
        model_used = response.model or "unknown"
        self._ensure_dirs()
        self._track_usage(tokens_used)

        parsed = response.choices[0].message.parsed
        if not parsed:
            return InitResult(files_created=[], tokens_used=tokens_used, model_used=model_used)
        files_created: list[str] = []
        for f in parsed.files:
            # Normalize: LLM sometimes returns .claude/CLAUDE.md instead of CLAUDE.md
            path = f.path
            if path in (".claude/CLAUDE.md", ".claude\\CLAUDE.md"):
                path = "CLAUDE.md"
            fpath = project_root / path
            fpath.parent.mkdir(parents=True, exist_ok=True)
            fpath.write_text(f.content, encoding="utf-8")
            files_created.append(path)

        return InitResult(
            files_created=files_created,
            tokens_used=tokens_used,
            model_used=model_used,
        )
