"""Configure the GraphRAG 3.3.0 short-sample project with loopback models."""

from importlib.metadata import version
from pathlib import Path

import yaml

if version("graphrag") != "3.3.0":
    raise SystemExit("This example requires GraphRAG 3.3.0.")

settings = Path("settings.yaml")
prompts_dir = Path("prompts")
if not settings.is_file() or not prompts_dir.is_dir():
    raise SystemExit("Run graphrag init in a new project directory first.")
if Path("output").exists():
    raise SystemExit("Use a new project directory without index output.")

config = yaml.safe_load(settings.read_text(encoding="utf-8"))
for group, name, port in (
    ("completion_models", "local-chat", 18504),
    ("embedding_models", "local-embed", 18505),
):
    model, = config[group].values()
    model.update(
        model_provider="openai",
        model=name,
        api_key="local-test",
        api_base=f"http://127.0.0.1:{port}/v1",
        retry={"type": "immediate", "max_retries": 2},
        call_args={"timeout": 120},
    )
    if group == "completion_models":
        model["call_args"].update(temperature=0, max_tokens=2200, seed=42)

config["concurrent_requests"] = 1
config["extract_graph"].update(entity_types=["PERSON"], max_gleanings=0)
config["community_reports"].update(max_length=350, max_input_length=5000)
config["global_search"].update(data_max_tokens=4000, max_context_tokens=4000, concurrent_requests=1)
config["local_search"]["max_context_tokens"] = 4000

prompts = {
    ("extract_graph", "prompt"): """Extract {entity_types} and explicit relationships from the text. List every person before relationships. Use uppercase full names that match the entity names exactly. Preserve direction in the relationship description. Use these records, literal delimiters, numeric fifth fields for relationships, and no extra text.
Example input: Alina Chen and Ben Jones were partners. Celia Park invited Alina Chen to lunch.
Example output:
("entity"<|>ALINA CHEN<|>PERSON<|>Alina Chen was a partner of Ben Jones.)##
("entity"<|>BEN JONES<|>PERSON<|>Ben Jones was a partner of Alina Chen.)##
("entity"<|>CELIA PARK<|>PERSON<|>Celia Park invited Alina Chen to lunch.)##
("relationship"<|>ALINA CHEN<|>BEN JONES<|>Alina Chen and Ben Jones were partners.<|>9)##
("relationship"<|>CELIA PARK<|>ALINA CHEN<|>Celia Park invited Alina Chen to lunch.<|>9)<|COMPLETE|>
Input:
{input_text}
Output:
""",
    ("community_reports", "graph_prompt"): """Write a report based only on the supplied relationship descriptions. In both summary and findings preserve the direction of each action. Include every explicit relation, including both facts if a relation has two. One finding per relationship. Do not infer anything. Return a JSON object with title (string), summary (string), rating (0-10), rating_explanation (string), and findings (array of objects with summary and explanation strings). At most {max_report_length} words. Copy each relationship description exactly into the findings. Use its exact sentence as the explanation. In the summary, repeat the three relationship descriptions verbatim.
Data:
{input_text}
""",
    ("global_search", "map_prompt"): """Return JSON with a points array. For each relevant sentence, copy it exactly and append a citation using the numeric ID of the row. The ID is the first column in the table. A point without a citation is invalid.
Example for an unrelated report with id 91: {{"points":[{{"description":"Mei visited Pat. [Data: Reports (91)]","score":100}}]}}.
Use the displayed reports, copy relevant sentences and cite the actual report ID. Limit {max_length} words.
Rows:
{context_data}
""",
    ("global_search", "reduce_prompt"): """Answer as {response_type} using only these analyst points. Return each point exactly as supplied, one per line, including the bracketed Data: Reports citation at the end of the line. Discard any point without a citation. Output only those lines. Maximum {max_length} words.
{report_data}
""",
    ("local_search", "prompt"): """Respond as {response_type}. Copy each relevant sentence from the Sources section into a bullet. Finish every bullet with a citation using the numeric ID of that Sources row. For an unrelated source with id 91, a complete bullet would read: "- Mei visited Pat. [Data: Sources (91)]". Use the actual source row and ID shown here. Print only the bullets.
{context_data}
""",
}

for (group, key), prompt in prompts.items():
    path = prompts_dir / f"short_sample_{group}_{key}.txt"
    path.write_text(prompt, encoding="utf-8")
    config[group][key] = path.as_posix()

settings.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
print("Configured GraphRAG 3.3.0 for the three-sentence example.")
